<template>
  <div class="pageStyle">
    <div style="display: flex;">
      <ElScrollbar class="map-left">
        <div class="airline-header mg-b-10">
          <p class="fs-16 fw-bold" style="margin-left:8px">航线概览</p>
          <ElButton class="btn" style="margin-right: 8px;" link type="primary" @click="handleBack()">返回</ElButton>
        </div>
        <div class="airline-distance">
          <div class="flex-1">
            <p class="fs-14" style="font-weight: 800; line-height: 24px">{{ airlineList ? airlineList.length : 0 }}</p>
            <p style="font-size: 12px; line-height: 24px; color: #606266">
              航点数
            </p>
          </div>
          <div class="flex-1">
            <p class="fs-14" style="font-weight: 800; line-height: 24px">
              {{ formyaw.totalDistance ? formyaw.totalDistance.toFixed(0) : 0 }}m</p>
            <p style="font-size: 12px; line-height: 24px; color: #606266">
              预计飞行里程
            </p>
          </div>
          <div class="flex-1">
            <p class="fs-14" style="font-weight: 800; line-height: 24px">{{ formattedTotalTime }}</p>
            <p style="font-size: 12px; line-height: 24px; color: #606266">
              预计飞行时长
            </p>
          </div>
        </div>
        <div class="airline-stoproute mg-b-10" @click="airlineClick(index)" v-for="(it, index) in airlineList"
          :key="index" :class="selectedWayPoint == it ? 'airline-distanceblue' : ''">
          <p class="mg-b-20 fw-5 fs-14">
            <span>{{ it.wayPointName }}</span>
            <span>（飞行高度：{{ it.height }} m）</span>
          </p>
          <div class="mg-b-10" style="display: flex;">
            <span class="fs-14" style="width: 75px; color: #606266">航点动作</span>
            <section style="width: calc(100% - 75px);" v-if="it.actions.length > 0">
              <div class="bgimg" style="width: calc(100% / 6.8);" v-for="(item, index) in it.actions" :key="index"
                :title="item.name">
                <ElTooltip effect="light" :content="item.name" placement="top">
                  <img :src="getwayList(item.actionType)?.url || '/static/action1.png'" alt="" />
                </ElTooltip>
              </div>
            </section>
            <span v-else class="fs-14" style="color: #606266">暂无数据</span>
          </div>
          <div class="flex-row-center">
            <span class="fs-14" style="width: 75px; color: #606266">航段</span>
            <section style="width: calc(100% - 75px);" v-if="it.algorithmIds && it.algorithmIds.length > 0">
              <div class="bgimg" style="width: calc(100% / 5.5);" v-for="(item, index) in it.algorithmIds" :key="index"
                :title="getalgorithmList(item)?.label || ''">
                <ElTooltip effect="light" :content="getalgorithmList(item)?.label || ''" placement="top">
                  <img :src="getalgorithmList(item)?.url || '/static/action1.png'" alt="" />
                </ElTooltip>
              </div>
            </section>
            <span v-else class="fs-14" style="color: #606266">暂无数据</span>
          </div>
        </div>
        <div style="width: 100%;height: 30px;"></div>
        <div class="pd-10" style="width: 100%;">
          <p class="backbtn" link type="primary" v-if="router.currentRoute.value.query.id"
            @click="savetwo('saveAllEdit')">保存并退出</p>
          <p class="backbtn" link type="primary" v-else @click="savetwo('saveAll')">保存并退出</p>
        </div>
      </ElScrollbar>
      <mapPosition ref="mapRef" style="width: 100%" :flayShow="flayShow" :airportList="airportList"
        :flayoneShow="flayoneShow" :flightaltitude="Number(form.globalHeight)"
        :safetakeoffaltitude="Number(form.takeOffSecurityHeight)" :selectedWayPoint="selectedWayPoint"
        @drawingnext="getdrawingNext" @delSetTakeoffMode="setTakeoffMode" @deloneSetTakeoffMode="oneSetTakeoffMode"
        @allData="getallData" @totalDistance="gettotalDistance" @distanceArray="getdistanceArray"
        @waypointDoubleClick="waypointDoubleClick" :drawDefaultRoute="drawDefaultRoute" :airlineList="airlineList" />
      <ElScrollbar class="map-right">
        <div class="airline-img mg-b-10">
          <div class="airline-setting flex-row-center" style="margin-bottom: 8px;">
            <p class="fs-14 fw-5">航线名称</p>
            <p class="text" style="font-size: 12px; margin-right: 8px;cursor: pointer;color: #409EFF;"
              v-if="!showEditAirlineName" @click="editAirlineName">
              编辑
            </p>
            <section v-if="showEditAirlineName">
              <span class="text" style="font-size: 12px; margin-right: 8px;cursor: pointer;color: #006be6;"
                @click="cancelAirlineNameEdit">取消</span>
              <span class="text" style="font-size: 12px; margin-right: 8px;cursor: pointer;color: #006be6;"
                @click="saveAirlineName" :class="{ 'disabled-button': !isAirlineNameValid }"
                :disabled="!isAirlineNameValid">确定</span>
            </section>
          </div>
          <div v-if="!showEditAirlineName">
            <ElTooltip effect="light" :content="ruleForm.airlineNameData" placement="top">
              <p class="fs-16 fw-bold"
                style="text-align: left; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis; word-wrap: break-word; word-break: break-all; line-height: 1.5em; max-height: 3em;">
                {{ ruleForm.airlineNameData }}</p>
            </ElTooltip>
          </div>
          <div v-if="showEditAirlineName" style="position: relative;">
            <ElForm ref="ruleFormRef" :model="ruleForm" :rules="rules">
              <ElFormItem label="" prop="airlineNameData">
                <!-- v-model="airlineNameData"  -->
                <ElInput v-model="ruleForm.airlineNameData" style="width: 100%;" maxlength="20" show-word-limit
                  type="textarea" autosize placeholder="请输入航线名称" @keydown.enter.prevent="handleEnterKey"
                  @keydown.space.prevent @input="debouncedHandleAirlineNameInput" @keydown="handleAirlineNameKeydown">
                </ElInput>
              </ElFormItem>
            </ElForm>
          </div>
        </div>
        <div class="airline-setup">
          <div class="tab-item fw-5" style="border-right: 1px solid #DCDFE6;cursor: pointer;" @click="activeName = '1'"
            :class="activeName == '1' ? 'tab-itemBg' : ''">
            航线设置
          </div>
          <div style="cursor: pointer;" class="fw-5" @click="getActiveName('2')"
            :class="activeName == '2' ? 'tab-itemBg' : ''">
            航点设置
          </div>
        </div>
        <div v-if="activeName == '1'">
          <div class="flex-row-center airline-fly">
            <p class="fs-14 fw-5">参考起飞点</p>
            <p class="flex-row-center text fs-14" style="cursor: pointer;">
              <img src="/static/flay.png" alt="" />
              <span v-show="flayoneShow" @click="oneSetTakeoffMode(false)">参考起飞点未设置</span>
            <section v-if="!flayoneShow">
              <span v-if="!isResettingTakeoff" @click="enterResetTakeoffMode">重设起飞点</span>
              <span v-if="isResettingTakeoff" @click="cancelResetTakeoffMode">取消设置</span>
            </section>
            </p>
          </div>

          <div class="airline-img mg-b-10">
            <p class="fs-14 fw-5">照片存储类型</p>
            <!-- <ElCheckbox label="广角照片" v-model="form.wideType"></ElCheckbox>
            <ElCheckbox label="变焦照片" v-model="form.zoomType"></ElCheckbox> -->
            <ElCheckbox label="可见光" v-model="form.visableType" @change="autoSave"></ElCheckbox>
            <ElCheckbox label="红外照片" v-model="form.irType" @change="autoSave"></ElCheckbox>
          </div>
          <div class="airline-img mg-b-10">
            <div class="select-container">
              <span class="select-label">无人机品牌</span>
              <ElSelect v-model="form.brandId" placeholder="请选择无人机品牌" @change="changeBrand" style="width: 100%;"
                class="brand-select">
                <ElOption v-for="item in brandOptions" :key="item.id" :label="item.brandName" :value="item.id" />
              </ElSelect>
            </div>
            <div class="select-container">
              <span class="select-label">系列</span>
              <ElSelect v-model="form.seriesId" placeholder="请选择无人机系列" @change="selectSeries" style="width: 100%;">
                <ElOption v-for="item in seriesList" :key="item.id" :label="item.seriesName" :value="item.id" />
              </ElSelect>
            </div>
            <div class="select-container">
              <span class="select-label">型号</span>
              <ElSelect v-model="form.modelId" placeholder="请选择无人机型号" @change="selectModel" style="width: 100%;">
                <ElOption v-for="item in currentModels" :key="item.id" :label="item.modelName" :value="item.id" />
              </ElSelect>
            </div>
          </div>
          <div class="airline-img mg-b-10">
            <p class="fs-14 fw-5">航线高度模式</p>
            <div class="btn">
              <p style="cursor: pointer;" :class="form.airlineHeightType == 0 ? 'activeBtn' : ''"
                @click="getheightmode(0)">
                <span>相对起飞点高度</span>
              </p>
              <p style="cursor: pointer;" :class="form.airlineHeightType == 1 ? 'activeBtn' : ''"
                @click="getheightmode(1)">
                <span>相对地面高度</span>
              </p>
              <p style="margin-left: 8px;cursor: pointer;" :class="form.airlineHeightType == 2 ? 'activeBtn' : ''"
                @click="getheightmode(2)">
                <span>绝对高度</span>
              </p>
            </div>
          </div>
          <div class="pd-10 mg-b-10"
            style="margin: 8px;background: #fff;border: 1px solid #DCDFE6; border-radius: 4px;">
            <div class="airline-setting flex-row-center">
              <p class="fs-14 fw-5">飞行高度</p>
              <p class="text">
                <ElInputNumber v-model="form.globalHeight" :precision="1" :step="1" :min="min" :max="max"
                  @blur="handleBlur($event, 'globalHeight')" @change="handleGlobalHeightChange" style="width: 75px"
                  :controls="false"></ElInputNumber>
                <span class="m-l-5" style="font-size: 12px">m</span>
              </p>
            </div>
            <div class="airline-slider">
              <img style="margin: 0;cursor: pointer;" src="/static/delete.png" @click="flightaltitudeClick('-')"
                :style="{ cursor: form.globalHeight <= min ? 'not-allowed' : 'pointer' }" alt="" />
              <ElSlider v-model="sliderGlobalHeight" :min="min" :max="max" :step="1" :show-tooltip="true"
                @change="handleGlobalHeightChange" :format-tooltip="(val) => `${parseFloat(val).toFixed(1)}m`">
              </ElSlider>
              <img style="margin: 0;cursor: pointer;" @click="flightaltitudeClick('+')"
                :style="{ cursor: form.globalHeight >= max ? 'not-allowed' : 'pointer' }" src="/static/add.png"
                alt="" />
            </div>
            <div class="airline-setting flex-row-center">
              <p class="fs-14 fw-5">飞行速度</p>
              <p class="text">
                <ElInputNumber v-model="form.autoFlightSpeed" :precision="1" :step="1" :min="minSpeed"
                  :max="maxflightspeed" @blur="handleBlur($event, 'autoFlightSpeed')" style="width: 75px"
                  :controls="false"></ElInputNumber>
                <span class="m-l-5" style="font-size: 12px">m/s</span>
              </p>
            </div>
            <div class="airline-slider">
              <img style="margin: 0;cursor: pointer;" src="/static/delete.png" @click="flightspeedClick('-')"
                :style="{ cursor: form.autoFlightSpeed <= minSpeed ? 'not-allowed' : 'pointer' }" alt="" />
              <ElSlider v-model="sliderAutoFlightSpeed" :min="minSpeed" :max="maxflightspeed" :step="1"
                :show-tooltip="true" :format-tooltip="(val) => `${parseFloat(val).toFixed(1)}m/s`"></ElSlider>
              <img style="margin: 0;cursor: pointer;" src="/static/add.png" @click="flightspeedClick('+')"
                :style="{ cursor: form.autoFlightSpeed >= maxflightspeed ? 'not-allowed' : 'pointer' }" alt="" />
            </div>
            <div class="airline-setting flex-row-center">
              <p class="fs-14 fw-5">起飞速度</p>
              <p class="text">
                <ElInput v-model="form.globalTransitionalSpeed"
                  v-decimal-input="{ type: 'number', decimals: 1, min: minSpeed, max: maxflightspeed }"
                  @blur="handleBlur($event, 'globalTransitionalSpeed')" style="width: 75px"></ElInput>
                <span class="m-l-5" style="font-size: 12px">m/s</span>
              </p>
            </div>
            <div class="airline-slider">
              <img style="margin: 0;cursor: pointer;" src="/static/delete.png" @click="takeoffspeedClick('-')"
                :style="{ cursor: form.globalTransitionalSpeed <= minSpeed ? 'not-allowed' : 'pointer' }" alt="" />
              <ElSlider v-model="sliderGlobalTransitionalSpeed" :min="minSpeed" :max="maxflightspeed"></ElSlider>
              <img style="margin: 0;cursor: pointer;" src="/static/add.png" @click="takeoffspeedClick('+')"
                :style="{ cursor: form.globalTransitionalSpeed >= maxflightspeed ? 'not-allowed' : 'pointer' }"
                alt="" />
            </div>
          </div>
          <div class="airline-img mg-b-10">
            <p class="fs-14 fw-5">无人机偏航角</p>
            <ElSelect class="select" v-model="form.attitudeHead" placeholder="请选择" @change="autoSave">
              <ElOption v-for="item in yawList" :key="item.value" :label="item.label" :value="item.value" />
            </ElSelect>
          </div>
          <div class="airline-img mg-b-10">
            <p class="fs-14 fw-5">航点类型</p>
            <ElSelect class="select" v-model="form.wayPointType" placeholder="请选择" @change="autoSave">
              <ElOption v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
            </ElSelect>
          </div>
          <!-- <div class="airline-img mg-b-10" >
            <p class="fs-14">无人机失控动作</p>
            <ElSelect
              class="select"
              v-model="form.outOfControlAction"
              placeholder="请选择"
              @change="autoSave"
            >
              <ElOption
                v-for="item in destinationtypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </ElSelect>
          </div> -->
          <div class="airline-img mg-b-20">
            <p class="fs-14">无人机完成动作</p>
            <ElSelect class="select" v-model="form.finishAction" placeholder="请选择">
              <ElOption v-for="item in destinationtypeList" :key="item.value" :label="item.label" :value="item.value" />
            </ElSelect>
          </div>
          <div class="pd-10 mg-b-10"
            style="margin: 8px;background: #fff;border: 1px solid #DCDFE6; border-radius: 4px;">
            <div class="airline-setting flex-row-center">
              <p class="fs-14 fw-5">安全起飞高度</p>
              <p class="text">
                <ElInputNumber v-model="form.takeOffSecurityHeight" :precision="1" :step="1" :min="1" :max="500"
                  @blur="handleBlur($event, 'takeOffSecurityHeight')" style="width: 75px" :controls="false">
                </ElInputNumber>
                <span class="m-l-5">m</span>
              </p>
            </div>
            <div class="airline-slider">
              <img style="margin: 0;cursor: pointer;" src="/static/delete.png" @click="safetakeoffaltitudeClick('-')"
                :style="{ cursor: form.takeOffSecurityHeight <= 1 ? 'not-allowed' : 'pointer' }" alt="" />
              <ElSlider v-model="sliderTakeOffSecurityHeight" :min="1" :max="500" :step="1" :show-tooltip="true"
                :format-tooltip="(val) => `${parseFloat(val).toFixed(1)}m`"></ElSlider>
              <img style="margin: 0;cursor: pointer;" src="/static/add.png" @click="safetakeoffaltitudeClick('+')"
                :style="{ cursor: form.takeOffSecurityHeight >= 500 ? 'not-allowed' : 'pointer' }" alt="" />
            </div>
            <div class="airline-setting flex-row-center">
              <p class="fs-14 fw-5">返航高度</p>
              <p class="text">
                <ElInputNumber v-model="form.globalRTHHeight" :precision="1" :step="1" :min="1" :max="500"
                  @blur="handleBlur($event, 'globalRTHHeight')" style="width: 75px" :controls="false"></ElInputNumber>
                <span class="m-l-5">m</span>
              </p>
            </div>
            <div class="airline-slider">
              <img style="margin: 0;cursor: pointer;" src="/static/delete.png" @click="returnaltitudeClick('-')"
                :style="{ cursor: form.globalRTHHeight <= 1 ? 'not-allowed' : 'pointer' }" alt="" />
              <ElSlider v-model="sliderGlobalRTHHeight" :min="1" :max="500" :step="1" :show-tooltip="true"
                :format-tooltip="(val) => `${parseFloat(val).toFixed(1)}m`"></ElSlider>
              <img style="margin: 0;cursor: pointer;" src="/static/add.png" @click="returnaltitudeClick('+')"
                :style="{ cursor: form.globalRTHHeight >= 500 ? 'not-allowed' : 'pointer' }" alt="" />
            </div>
          </div>
          <ElButton class="save" type="primary" @click="saveline(ruleFormRef)">保存设置</ElButton>
        </div>
        <div v-else>
          <div style="margin: 8px">
            <ElSelect class="select" v-model="formyaw.wayPointName" placeholder="请选择" @change="getstopenroute"
              @visible-change="showDataloading = false">
              <!-- <ElOption
                v-for="(item,index) in allData[0].points"
                :key="index"
                :label="'航点'+(index+1)"
                :value="index"
              /> -->
              <ElOption v-for="(item, index) in airlineList" :key="index" :label="item.wayPointName" :value="index" />
            </ElSelect>
          </div>
          <section v-loading="showDataloading" element-loading-text="加载中...">
            <div style="background: #fff; border-radius: 4px" class="airline-img pd-10 mg-b-10">
              <div style="padding: 0">
                <p class="fs-14 fw-5">坐标设置</p>
                <ElRadioGroup class="checkbox" v-model="formyaw.positionType" @change="updatemap()">
                  <ElRadio label="WGS84" :value="0" />
                  <ElRadio label="百度" :value="1" />
                  <ElRadio label="高德" :value="2" />
                  <ElRadio label="大地2000" :value="3" />
                </ElRadioGroup>
              </div>
              <div class="airline-setting flex-row-center" style="margin-top: 5px;">
                <p class="fs-14" style="width: 15%">经度</p>
                <ElInput v-model="formyaw.longitude" style="width: 85%" @change="updateWaypointCoordinates"
                  @input="validateCoordinate" class="address"></ElInput>
                <span class="du">°</span>
              </div>
              <div class="airline-setting flex-row-center" style="margin-top: 10px">
                <p class="fs-14" style="width: 15%">纬度</p>
                <ElInput v-model="formyaw.latitude" style="width: 85%" @change="updateWaypointCoordinates"
                  @input="validateCoordinate" class="address"></ElInput>
                <span class="du">°</span>
              </div>
            </div>
            <div style="background: #fff; border-radius: 4px" class="airline-img pd-10 mg-b-10">
              <div class="airline-setting flex-row-center">
                <p class="fs-14 fw-5">飞行高度</p>
                <ElCheckbox label="跟随航线" @change="linealtitudeClick" v-model="formyaw.heightFollow" :true-value="1"
                  :false-value="0" style="font-size: 12px;" />
                <p class="text">
                  <ElInputNumber v-model.number.lazy="formyaw.height" @change="changeFlightaltitude"
                    @blur="handleFlightaltitudeBlur" style="width: 75px" :controls="false" :precision="1" :step="1"
                    :min="min" :max="max"></ElInputNumber>
                  <span class="m-l-5" style="font-size: 12px">m</span>
                </p>
              </div>
              <div class="airline-slider">
                <img style="margin: 0" src="/static/delete.png" @click="yawaltitudeClick('-')"
                  :disabled="formyaw.height <= min" alt="" />
                <ElSlider v-model="sliderFormyawHeight" @change="changeFlightaltitude" :min="min" :max="max" :step="1"
                  :show-tooltip="true" :format-tooltip="(val) => `${parseFloat(val).toFixed(1)}m`"></ElSlider>
                <img style="margin: 0" src="/static/add.png" @click="yawaltitudeClick('+')"
                  :disabled="formyaw.height >= max" alt="" />
              </div>
              <div class="airline-setting flex-row-center">
                <p class="fs-14 fw-5">飞行速度</p>
                <ElCheckbox label="跟随航线" @change="linespeedClick" :true-value="1" :false-value="0"
                  v-model="formyaw.waypointSpeedFollow" style="font-size: 12px;" />
                <p class="text">
                  <ElInputNumber v-model.number="formyaw.flightspeed" @change="changeFlightSpeed" style="width: 75px"
                    :controls="false" :precision="1" :step="1" :min="0" :max="maxflightspeed"></ElInputNumber>
                  <span class="m-l-5" style="font-size: 12px">m/s</span>
                </p>
              </div>
              <div class="airline-slider" style="margin-bottom: 0">
                <img style="margin: 0" src="/static/delete.png" @click="yawspeedClick('-')"
                  :disabled="formyaw.flightspeed <= 0" alt="" />
                <ElSlider :model-value="sliderFormyawFlightspeed" @update:model-value="val => {
                  const numVal = Number(val);
                  if (!isNaN(numVal)) {
                    formyaw.flightspeed = numVal;
                    changeFlightSpeed(numVal);
                  }
                }" :min="minSpeed" :max="maxflightspeed" :step="1" :show-tooltip="true"
                  :format-tooltip="(val) => `${parseFloat(val).toFixed(1)}m/s`" />
                <img style="margin: 0" src="/static/add.png" @click="yawspeedClick('+')"
                  :disabled="formyaw.flightspeed >= maxflightspeed" alt="" />
              </div>
            </div>
            <div class="airline-img mg-b-10">
              <p class="fs-14 fw-5">直播镜头模式</p>
              <ElRadioGroup class="checkbox" v-model="formyaw.imageFormat">
                <ElRadio label="广角" :value="0" />
                <ElRadio label="变焦" :value="1" />
                <ElRadio label="红外" :value="2" />
              </ElRadioGroup>
            </div>
            <div class="airline-img mg-b-10">
              <p class="fs-14 fw-5">无人机偏航角</p>
              <ElSelect class="select" v-model="formyaw.attitudeHead" placeholder="请选择" @change="updateyaw()">
                <ElOption v-for="item in yawList" :key="item.value" :label="item.label" :value="item.value" />
              </ElSelect>
            </div>
            <div class="pd-10 mg-b-10 airline-img" style="background: #fff; border-radius: 4px">
              <div class="flex-row-center" style="align-items: center;
    justify-content: space-between;padding: 0; margin: 0;">
                <p class="fs-14 fw-5">航点动作</p>
                <ElButton type="primary" link @click="addClick(formyaw.actions)" style="font-size: 12px;">添加动作
                </ElButton>
              </div>
              <div ref="actionsContainer" class="actions-container"
                style="display: flex; flex-direction: column; gap: 10px;">
                <div v-for="(item, index) in formyaw.actions" :key="item.id || `action-${item.actionType}-${index}`"
                  class="airline-wavy sortable-item"
                  style="margin-bottom: 0; background: #f9f9f9; border-radius: 4px; padding: 10px;" :data-index="index">
                  <div class="flex-row-center fs-14 justify-between">
                    <div class="bgimg flex-row-center sortable-handle"
                      style="display: flex; border-radius: 4px; cursor: move;" title="拖拽排序">
                      <img src="/static/action12.png" alt="" style="margin-right: 5px;" />
                      <span>{{ item.name }}</span>
                    </div>
                    <div class="flex-row-center">
                      <p class="text" style="margin-right: 10px;" v-if="
                        item.actionType == 1 ||
                        item.actionType == 2 ||
                        item.actionType == 3 ||
                        item.actionType == 7 ||
                        item.actionType == 9 ||
                        item.actionType == 10">
                        <ElInputNumber v-model.number="item.actionValue" style="width: 75px" :controls="false"
                          :precision="([2, 3, 7, 9].includes(item.actionType)) ? 1 : 0" :step="1" :min="item.actionMin"
                          :max="item.actionMax" @blur="(e) => handleActionValueBlur(item, e)"
                          @change="(val) => updateActionValue(item, val)"></ElInputNumber>
                        <span v-if="item.actionType == 1 || item.actionType == 10">S</span>
                        <span v-if="item.actionType == 2 || item.actionType == 3">°</span>
                        <span v-if="item.actionType == 7">X</span>
                        <span v-if="item.actionType == 9">m</span>
                      </p>
                      <Close width="16px" @click="deleteClick(item)" />
                    </div>
                  </div>
                  <div class="airline-slider" style="margin-bottom: 0; margin-top: 5px;" v-if="
                    item.actionType == 1 ||
                    item.actionType == 2 ||
                    item.actionType == 3 ||
                    item.actionType == 7 ||
                    item.actionType == 9 ||
                    item.actionType == 10">
                    <img style="margin: 0" src="/static/delete.png" @click="actionValueClick(item, '-')" alt="" />
                    <ElSlider :model-value="Number(item.actionValue)"
                      @update:model-value="val => updateActionValue(item, val)" :min="Number(item.actionMin)"
                      :max="Number(item.actionMax)" :step="1" :show-tooltip="true"
                      :format-tooltip="(val) => formatActionValueTooltip(item, val)"></ElSlider>
                    <img style="margin: 0" @click="actionValueClick(item, '+')" src="/static/add.png" alt="" />
                  </div>
                </div>
              </div>
            </div>
            <div class="airline-img mg-b-10">
              <p class="fs-14 fw-5">算法配置</p>
              <ElButton class="airBtn" @click="algorithmClick">配置算法</ElButton>
            </div>
            <div class="airline-img mg-b-10">
              <p class="fs-14 fw-5">喊话配置</p>
              <ElButton class="airBtn" @click="shoutClick">配置喊话</ElButton>
            </div>
            <ElButton class="save" type="primary" @click="saveList()">保存设置</ElButton>
          </section>
        </div>

      </ElScrollbar>
      <!-- 配置算法 -->
      <algorithmview v-if="algorithmFlag" @algoView="getalgoView" @getalgoSetting="getalgoSetting" @close="getClose"
        :algorithmConfig="algorithmConfig"></algorithmview>
      <!-- 配置喊话 -->
      <shoutview v-if="shoutFlag" @close="getClose" @getShoutview="getShoutview" :shoutList="shoutList"></shoutview>
    </div>
    <!-- 添加动作 -->
    <waypointaction v-if="waypointactionFlag" :action="formyaw.actions" @close="getClose" @wayView="getwayView">
    </waypointaction>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  onMounted,
  onBeforeUnmount,
  defineProps,
  computed,
  watch,
  nextTick,
} from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import Sortable from "sortablejs";
import {
  ElInput,
  ElButton,
  ElScrollbar,
  ElCheckboxGroup,
  ElCheckbox,
  ElSelect,
  ElOption,
  ElRadioGroup,
  ElRadio,
  ElSlider,
  ElTooltip,
  ElMessage,
  ElMessageBox,
  ElLoading,
  ElIcon,
  ElForm,
  ElFormItem,
  ElInputNumber,
} from "element-plus";
import algorithmview from "./algorithmview.vue";
import shoutview from "./shoutview.vue";
import waypointaction from "./waypointaction.vue";
import mapPosition from "./map.vue";
import { onBeforeRouteLeave } from "vue-router";
import { getAirportListNoPage } from "#/api/sys/equipment";
import { adjustValue } from "./mapdata";
import { router } from "#/router";
import {
  add,
  editAirline,
  getAirlineById,
  coordinateConversion,
  getBrandList,
  getModelList,
  addName,
  editName,
} from "#/api/task/airline";

// import mapPosition from './mapLine.vue';
import {
  yawList,
  typeList,
  stopenrouteList,
  getalgorithmList,
  getwayList,
  destinationtypeList,
} from "./datalist";

const props = defineProps({ showSearch: Boolean });
const airportList = ref([]);
const brandOptions = ref([]); //品牌列表
const seriesList = ref([]); //系列列表
const currentModels = ref([]); //型号列表
// 默认动作配置
const DEFAULT_ACTIONS = [
  {
    name: "无人机偏航角",
    actionType: 2,
    actionValue: 0,
    actionMin: -180,
    actionMax: 180,
    url: "/static/action2.png",
  },
  {
    name: "云台俯仰角",
    actionType: 3,
    actionValue: 0,
    actionMin: -120,
    actionMax: 45,
    url: "/static/action3.png",
  },
  {
    name: "相机变焦",
    actionType: 7,
    actionValue: 1,
    actionMin: 1,
    actionMax: 200,
    url: "/static/action7.png",
  },
];
const showEditAirlineName = ref(false); // 是否显示编辑航线名称
const actionsContainer = ref(null); // 动作容器引用，用于拖拽排序
const allData = ref([{ points: [] }]);
const drawDefaultRoute = ref([]); //默认航线数据
const ruleFormRef = ref();
const ruleForm = reactive({
  airlineNameData: router.currentRoute.value.query.airlineName,
});
const rules = reactive({
  airlineNameData: [
    { required: true, message: "请输入航线名称", trigger: "blur" },
    { min: 1, max: 20, message: "请输入最多20字", trigger: "blur" },
  ],
});
const totalTime = ref(0); //总飞行时间
const defaultList = ref([]); //默认航线数据
const gaodeList = ref([{ longitude: 0, latitude: 0 }]); //高德坐标默认
// 格式化飞行时间为分钟加秒钟格式
const formattedTotalTime = computed(() => {
  if (!totalTime.value || totalTime.value <= 0) {
    return "0min0s";
  }

  const totalSeconds = Math.round(totalTime.value);
  const minutes = Math.floor(totalSeconds / 60);
  const seconds = totalSeconds % 60;

  return `${minutes}min${seconds}s`;
});
const selectedWayPoint = ref(null); // 选中的航点

// 记录当前航点索引
const waypointIndex = ref(0);
const obj = {
  wayPointName: "",
  longitude: "",
  latitude: "",
  height: 0,
  positionType: 2, //地图
  waypointSpeed: 10,
  imageFormat: 0,
  attitudeHead: 0,
  heightFollow: 1,
  waypointSpeedFollow: 1,
  // actions: [...DEFAULT_ACTIONS],
  actions: [],
  algorithmIds: [],
  megaphoneOperate: {
    megaphoneOperateLoop: 0,
    megaphoneType: 0,
    megaphoneOperateFile: "",
    text: "",
    playVolume: 0,
  },
};

// 系列选择事件
const selectSeries = (value) => {
  // 检查是否有修改并提示
  if (hasDroneTypeChanged()) {
    ElMessage({
      plain: true,
      message: "更改无人机类型将影响航线作业参数，请谨慎操作!",
      type: "warning",
    });
  }

  form.seriesId = value;
  const selectedSeries = seriesList.value.find((series) => series.id == value);
  if (selectedSeries) {
    currentModels.value = selectedSeries.models || [];
    // 默认选中第一个型号
    if (selectedSeries.models && selectedSeries.models.length > 0) {
      form.modelId = selectedSeries.models[0].id;
    } else {
      form.modelId = "";
    }
  } else {
    currentModels.value = [];
    form.modelId = "";
  }
};

// 型号选择事件
const selectModel = (value) => {
  // 检查是否有修改并提示
  if (hasDroneTypeChanged()) {
    ElMessage({
      plain: true,
      message: "更改无人机类型将影响航线作业参数，请谨慎操作!",
      type: "warning",
    });
  }

  form.modelId = value;
};
const airlineList = ref([]);
const shoutList = ref();
const distanceArray = ref([]);
// const airlineNameData = ref(router.currentRoute.value.query.airlineName);
const airlineform = reactive({
  //表单数据
  airlineHeightType: 0, //航线高度模式  0相对起飞点高度 1相对地面高度 2绝对高度
  // wideType: false, //广角照片
  // zoomType: false, //变焦照片
  irType: true, //红外照片
  visableType: true, //可见光照片
  globalHeight: 120, //飞行高度
  autoFlightSpeed: 10, //飞行速度
  globalTransitionalSpeed: 10, //起飞速度
  attitudeHead: 0, //偏航角
  wayPointType: 1, //航点类型
  outOfControlAction: 0, //无人机失控
  finishAction: 0, //无人机完成动作
  takeOffSecurityHeight: 120, //安全起飞高度
  globalRTHHeight: 120, //返航高度
  brandId: router.currentRoute.value.query.brandId,
  seriesId: router.currentRoute.value.query.seriesId,
  modelId: router.currentRoute.value.query.modelId,
});

const form = reactive({
  airlineName: router.currentRoute.value.query.airlineName || "", // 航线名称，从路由参数获取
  airlineHeightType: 0, //航线高度模式  0相对起飞点高度 1相对地面高度 2绝对高度
  globalHeight: 100, //飞行高度
  autoFlightSpeed: 10, //飞行速度
  globalTransitionalSpeed: 10, //起飞速度
  attitudeHead: 0, //偏航角
  wayPointType: 1, //航点类型
  outOfControlAction: 0, //无人机失控
  finishAction: 0, //无人机完成动作
  takeOffSecurityHeight: 120, //安全起飞高度
  globalRTHHeight: 120, //返航高度
  // wideType: true, //广角照片 0:选中 1:未选中
  // zoomType: true, //变焦照片
  irType: true, //红外照片
  visableType: true, //可见光照片
  // wayPoints: [{
  // wayPointName: "", //航点名称
  // positionType: 2, //地图
  // longitude: null, //经度
  // latitude: null, //纬度
  // height: 0, //飞行高度
  // flightspeed: 0, //飞行速度
  // imageFormat: 0, //镜头模式
  // attitudeHead: 0, //偏航角
  // actions: [], //航点动作
  // algorithm: [], //配置算法id集合
  // shout: {}, //配置喊话
  // totalDistance: 0, //总距离
  // algorithmExtends: [], //算法配置
  // heightFollow: 1, //跟随航线高度
  // waypointSpeedFollow: 1, //跟随航线速度
  // }], //航点
});

// 保存初始无人机类型的值，用于比较是否有修改
const initialDroneType = {
  brandId: form.brandId,
  seriesId: form.seriesId,
  modelId: form.modelId,
};

// 检查无人机类型是否有修改
const hasDroneTypeChanged = () => {
  return (
    form.brandId !== initialDroneType.brandId ||
    form.seriesId !== initialDroneType.seriesId ||
    form.modelId !== initialDroneType.modelId
  );
};

// 处理回车键事件，防止换行
const handleEnterKey = (event) => {
  // 阻止默认的换行行为
  event.preventDefault();
  // 可以选择在这里触发保存或其他操作
  // 例如：失去焦点或触发保存
  event.target.blur();
};

// 处理航线名称输入，去除空格和换行符
const handleAirlineNameInput = (value) => {
  // 去除所有空格和换行符
  const cleanedValue = value.replace(/[\s]/g, "");
  if (cleanedValue !== value) {
    ruleForm.airlineNameData = cleanedValue;
  }
};

// 防抖函数
const debounce = (func, wait) => {
  let timeout;
  return function executedFunction (...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};

// 防抖版本的输入处理函数
const debouncedHandleAirlineNameInput = debounce((value) => {
  // 去除所有空格和换行符
  const cleanedValue = value.replace(/[\s]/g, "");
  if (cleanedValue !== value) {
    ruleForm.airlineNameData = cleanedValue;
  }
}, 100);

// 处理航线名称按键事件，阻止空格和换行符输入
const handleAirlineNameKeydown = (event) => {
  // 阻止空格键（包括普通空格、制表符等）
  if (event.key === " " || event.key === "Spacebar" || event.keyCode === 32) {
    event.preventDefault();
    return false;
  }
  // 阻止换行键
  if (event.key === "Enter" || event.keyCode === 13) {
    event.preventDefault();
    return false;
  }
};

// 修改 changeBrand 函数
const changeBrand = async () => {
  // 检查是否有修改并提示
  if (hasDroneTypeChanged()) {
    ElMessage({
      plain: true,
      message: "更改无人机类型将影响航线作业参数，请谨慎操作!",
      type: "warning",
    });
  }

  if (!form.brandId) {
    seriesList.value = [];
    currentModels.value = [];
    form.seriesId = "";
    form.modelId = "";
    return;
  }

  await getSeriesByBrandId();
};

// 计算属性确保传递给ElSlider的值是数字类型
const sliderGlobalHeight = computed({
  get: () => {
    const value = Number(form.globalHeight);
    return isNaN(value) ? min.value : parseFloat(value.toFixed(1));
  },
  set: (value) => {
    const newHeight = parseFloat(Number(value).toFixed(1));
    form.globalHeight = newHeight;

    // 只更新勾选了"跟随航线"的航点高度
    if (airlineList.value && airlineList.value.length > 0) {
      const updatedList = airlineList.value.map((item, index) => {
        // 创建新对象确保响应式更新，同时保留所有属性
        const newItem = {
          ...item,
          height: item.heightFollow === 1 ? newHeight : item.height
        };

        // 检查未跟随航线的航点，如果高度变得与航线高度一致，则自动勾选跟随
        if (item.heightFollow === 0) {
          const heightDiff = Math.abs(item.height - newHeight);
          if (heightDiff < 0.01) {
            newItem.heightFollow = 1;
          }
        }

        return newItem;
      });

      // 强制触发响应式更新
      airlineList.value = updatedList;
    }

    // 使用防抖函数来处理频繁的Slider值变化
    debounceUpdateFollowingWaypointsHeight(value);
  },
});


// 修改速度相关的计算属性
const sliderAutoFlightSpeed = computed({
  get: () => {
    const value = Number(form.autoFlightSpeed);
    // 限制在速度范围内
    if (isNaN(value) || value < minSpeed.value) return minSpeed.value;
    if (value > maxflightspeed.value) return maxflightspeed.value;
    return parseFloat(value.toFixed(1));
  },
  set: (value) => {
    const numValue = parseFloat(Number(value).toFixed(1));
    if (isNaN(numValue)) {
      form.autoFlightSpeed = minSpeed.value;
    } else if (numValue < minSpeed.value) {
      form.autoFlightSpeed = minSpeed.value;
    } else if (numValue > maxflightspeed.value) {
      form.autoFlightSpeed = maxflightspeed.value;
    } else {
      form.autoFlightSpeed = numValue;
    }

    // 更新所有跟随航线速度的航点
    if (airlineList.value && airlineList.value.length > 0) {
      airlineList.value.forEach((item) => {
        if (item.waypointSpeedFollow == 1) {
          item.waypointSpeed = form.autoFlightSpeed;
        }
        // 检查航点速度是否与航线速度一致，如果不一致则取消跟随（使用精度比较）
        const speedDiff = Math.abs(item.waypointSpeed - form.autoFlightSpeed);
        if (speedDiff >= 0.01) {
          item.waypointSpeedFollow = 0;
        }
      });
      // 强制触发响应式更新
      airlineList.value = [...airlineList.value];
    }
  },
});

const sliderGlobalTransitionalSpeed = computed({
  get: () => {
    const value = Number(form.globalTransitionalSpeed);
    // 限制在速度范围内
    if (isNaN(value) || value < minSpeed.value) return minSpeed.value;
    if (value > maxflightspeed.value) return maxflightspeed.value;
    return value;
  },
  set: (value) => {
    const numValue = Number(value);
    if (isNaN(numValue)) {
      form.globalTransitionalSpeed = minSpeed.value;
    } else if (numValue < minSpeed.value) {
      form.globalTransitionalSpeed = minSpeed.value;
    } else if (numValue > maxflightspeed.value) {
      form.globalTransitionalSpeed = maxflightspeed.value;
    } else {
      form.globalTransitionalSpeed = numValue;
    }
  },
});

const sliderTakeOffSecurityHeight = computed({
  get: () => Number(form.takeOffSecurityHeight),
  set: (value) => {
    // 保留一位小数
    form.takeOffSecurityHeight = parseFloat(Number(value).toFixed(1));
  },
});

const sliderGlobalRTHHeight = computed({
  get: () => Number(form.globalRTHHeight),
  set: (value) => {
    // 保留一位小数
    form.globalRTHHeight = parseFloat(Number(value).toFixed(1));
  },
});

const formyaw = reactive({
  wayPointName: "", //航点名称
  positionType: 2, //地图
  longitude: null, //经度
  latitude: null, //纬度
  height: 100, //飞行高度
  flightspeed: 10, //飞行速度
  imageFormat: 0, //镜头模式
  attitudeHead: 0, //偏航角
  actions: [], //航点动作
  algorithm: [], //配置算法id集合
  shout: {}, //配置喊话
  totalDistance: 0, //总距离
  algorithmExtends: [], //算法配置
  heightFollow: 1, //跟随航线高度
  waypointSpeedFollow: 1, //跟随航线速度
});

const sliderFormyawHeight = computed({
  get: () => {
    // 处理 null, undefined, 或空字符串的情况，设置默认值为0
    if (
      formyaw.height === null ||
      formyaw.height === undefined ||
      formyaw.height === ""
    ) {
      return 0;
    }
    const value = Number(formyaw.height);
    return isNaN(value) ? 0 : parseFloat(value.toFixed(1));
  },
  set: (value) => {
    // 通过 setter 传入的 value 通常是由 Slider 组件保证的数字
    formyaw.height = parseFloat(Number(value).toFixed(1));

    // 更新跟随状态 - 使用精度比较
    const heightDiff = Math.abs(formyaw.height - form.globalHeight);
    formyaw.heightFollow = heightDiff < 0.01 ? 1 : 0;

    // 更新航点数据
    if (
      airlineList.value &&
      airlineList.value[waypointIndex.value] !== undefined
    ) {
      airlineList.value[waypointIndex.value].height = formyaw.height;
      airlineList.value[waypointIndex.value].heightFollow = formyaw.heightFollow;
      // 强制触发响应式更新
      airlineList.value = [...airlineList.value];
    }

    // 触发自动保存
    // autoSave();
  },
});

const sliderFormyawFlightspeed = computed({
  get: () => {
    // 确保返回的是数字类型
    const value = Number(formyaw.flightspeed);
    // 航点速度最小值为0，最大值为maxflightspeed.value
    if (isNaN(value) || value < 0) return 0;
    if (value > maxflightspeed.value) return maxflightspeed.value;
    return parseFloat(value.toFixed(1));
  },
  set: (value) => {
    // 确保设置的是数字类型并保留一位小数
    const numValue = parseFloat(Number(value).toFixed(1));
    if (isNaN(numValue) || numValue < 0) {
      formyaw.flightspeed = 0;
    } else if (numValue > maxflightspeed.value) {
      formyaw.flightspeed = maxflightspeed.value;
    } else {
      formyaw.flightspeed = numValue;
    }

    // 更新跟随状态 - 只有当航点速度与航线速度一致时才勾选跟随（使用精度比较）
    const speedDiff = Math.abs(formyaw.flightspeed - form.autoFlightSpeed);
    formyaw.waypointSpeedFollow = speedDiff < 0.01 ? 1 : 0;

    // 更新航点数据
    if (
      airlineList.value &&
      airlineList.value[waypointIndex.value] !== undefined
    ) {
      airlineList.value[waypointIndex.value].waypointSpeed = formyaw.flightspeed;
      airlineList.value[waypointIndex.value].waypointSpeedFollow = formyaw.waypointSpeedFollow;

      // 强制触发响应式更新
      airlineList.value = [...airlineList.value];
    }

    // 触发自动保存
    // autoSave();
  },
});

// 为actionValue创建计算属性的辅助函数
const createActionValueComputed = (item) => {
  return computed({
    get: () => Number(item.actionValue),
    set: (value) => {
      item.actionValue = value;
    },
  });
};

// 算法
const algorithmList = ref([]);
const algorithmConfig = ref({
  algorithmList: algorithmList.value,
  algorithmExtends: formyaw.algorithmExtends,
});
const activeName = ref("1");
// const linealtitudeShow = ref(true); // 跟随航线高度选择框
// const linespeedShow = ref(true); // 跟随航线速度选择框
const linealtitude = ref(0); // 跟随航线高度
const linespeed = ref(0); // 跟随航线速度
const min = ref(1); // 最小值
const max = ref(500); // 最大值
const minSpeed = ref(1); // 最小速度
const maxflightspeed = ref(15); // 最大速度
const status = ref("");
const shoutFlag = ref(false);
const algorithmFlag = ref(false);
const waypointactionFlag = ref(false);
const flayShow = ref(true); // true 重设起飞点  fALSE取消设置
const flayoneShow = ref(true); // 参考起飞点未设置
const isResettingTakeoff = ref(false); // 是否正在重设起飞点模式
const showDataloading = ref(false);
// 添加用于控制自动保存的标志位
const isInitialLoad = ref(true); // 是否是首次加载
const hasTakeoffPoint = ref(false); // 是否有起飞点数据
const hasWaypointData = ref(false); // 是否有航点数据

// 添加自动保存防抖定时器
let autoSaveDebounceTimer = null;
const AUTO_SAVE_DEBOUNCE_DELAY = 500; // 500ms防抖延迟

// 获取系列列表
const getSeriesByBrandId = async () => {
  if (!form.brandId) return;

  const params = {
    brandId: form.brandId,
  };

  try {
    const { data } = await getModelList(params);
    seriesList.value = data || [];

    // 从路由参数中获取系列ID和型号ID，并转换为字符串类型
    const routeSeriesId = String(
      router.currentRoute.value.query.seriesId || ""
    );
    const routeModelId = String(router.currentRoute.value.query.modelId || "");

    // 如果路由中有系列ID，则设置并加载对应的型号
    if (
      routeSeriesId &&
      routeSeriesId !== "undefined" &&
      routeSeriesId !== "null"
    ) {
      // 查找对应的系列
      const selectedSeries = seriesList.value.find(
        (series) => String(series.id) === routeSeriesId
      );

      if (selectedSeries) {
        form.seriesId = selectedSeries.id;
        currentModels.value = selectedSeries.models || [];

        // 如果路由中有型号ID，则设置
        if (
          routeModelId &&
          routeModelId !== "undefined" &&
          routeModelId !== "null"
        ) {
          // 查找对应的型号
          const selectedModel = currentModels.value.find(
            (model) => String(model.id) === routeModelId
          );

          if (selectedModel) {
            form.modelId = selectedModel.id;
          } else if (currentModels.value.length > 0) {
            // 默认选中第一个型号
            form.modelId = currentModels.value[0].id;
          } else {
            form.modelId = "";
          }
        } else if (currentModels.value.length > 0) {
          // 默认选中第一个型号
          form.modelId = currentModels.value[0].id;
        } else {
          form.modelId = "";
        }
      } else if (seriesList.value.length > 0) {
        // 路由中的系列ID无效，默认选中第一个系列
        const firstSeries = seriesList.value[0];
        form.seriesId = firstSeries.id;
        currentModels.value = firstSeries.models || [];

        // 默认选中第一个型号
        if (currentModels.value.length > 0) {
          form.modelId = currentModels.value[0].id;
        } else {
          form.modelId = "";
        }
      } else {
        // 清空系列和型号
        form.seriesId = "";
        currentModels.value = [];
        form.modelId = "";
      }
    } else if (seriesList.value.length > 0) {
      // 默认选中第一个系列
      const firstSeries = seriesList.value[0];
      form.seriesId = firstSeries.id;
      currentModels.value = firstSeries.models || [];

      // 默认选中第一个型号
      if (currentModels.value.length > 0) {
        form.modelId = currentModels.value[0].id;
      } else {
        form.modelId = "";
      }
    } else {
      // 清空系列和型号
      form.seriesId = "";
      currentModels.value = [];
      form.modelId = "";
    }
  } catch (error) {
    ElMessage.error("获取系列列表失败");
    console.error(error);
  }
};

const handleBack = () => {
  let message = "若未保存数据将失效，确定要返回吗?";
  try {
    ElMessageBox.confirm(message, "提示", {
      type: "success",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      beforeClose: async (action, instance, done) => {
        if (action === "confirm") {
          instance.confirmButtonLoading = true;
          try {
            await router.go(-1);
            done();
          } catch (error) {
            instance.confirmButtonLoading = false;
            // 如果是取消导航，不显示错误
            if (error !== "cancel") {
              console.error("导航失败:", error);
            }
          }
        } else {
          done();
        }
      },
    });
  } catch (error) {
    // 忽略取消操作的错误
    if (error !== "cancel") {
      ElMessage.error(`退出失败: ${error.message || "未知错误"}`);
      console.error("退出失败:", error);
    }
  }
};

//坐标转换
const coordinateData = async (option) => {
  const params = {
    longitude: option.longitude,
    latitude: option.latitude,
    method: option.method,
  };
  const { data } = await coordinateConversion(params);
  return data;
};

// 飞行高度
const flightaltitudeClick = (option) => {
  let currentHeight =
    typeof form.globalHeight === "string"
      ? parseFloat(form.globalHeight)
      : Number(form.globalHeight);

  if (isNaN(currentHeight)) currentHeight = min.value;
  const change = option === "-" ? -1 : option === "+" ? 1 : 0;

  // 计算新值并确保在范围内
  let newHeight = currentHeight + change;
  newHeight = Math.max(min.value, Math.min(max.value, newHeight));

  // 保留一位小数
  const formattedNewHeight = parseFloat(newHeight.toFixed(1));
  form.globalHeight = formattedNewHeight;

  // 只更新勾选了"跟随航线"的航点高度
  if (airlineList.value && airlineList.value.length > 0) {
    const updatedList = airlineList.value.map((item, index) => {
      // 创建新对象确保响应式更新，同时保留所有属性
      const newItem = {
        ...item,
        height: item.heightFollow === 1 ? formattedNewHeight : item.height
      };

      // 检查未跟随航线的航点，如果高度变得与航线高度一致，则自动勾选跟随
      if (item.heightFollow === 0) {
        const heightDiff = Math.abs(item.height - formattedNewHeight);
        if (heightDiff < 0.01) {
          newItem.heightFollow = 1;
        }
      }

      return newItem;
    });

    // 强制触发响应式更新
    airlineList.value = updatedList;
  }

  // 使用防抖函数来处理频繁的值变化
  debounceUpdateFollowingWaypointsHeight(formattedNewHeight);
};

// 处理航线飞行高度变化事件
const handleGlobalHeightChange = (newVal, oldVal) => {
  // 确保新值是有效数字
  const numericNewVal = Number(newVal);
  if (isNaN(numericNewVal)) return;

  // 保留一位小数
  const formattedNewVal = parseFloat(numericNewVal.toFixed(1));
  form.globalHeight = formattedNewVal;

  // 只更新勾选了"跟随航线"的航点高度
  if (airlineList.value && airlineList.value.length > 0) {
    const updatedList = airlineList.value.map((item, index) => {
      // 创建新对象确保响应式更新，同时保留所有属性
      const newItem = {
        ...item,
        height: item.heightFollow === 1 ? formattedNewVal : item.height
      };

      // 检查未跟随航线的航点，如果高度变得与航线高度一致，则自动勾选跟随
      if (item.heightFollow === 0) {
        const heightDiff = Math.abs(item.height - formattedNewVal);
        if (heightDiff < 0.01) {
          newItem.heightFollow = 1;
        }
      }

      return newItem;
    });

    // 强制触发响应式更新
    airlineList.value = updatedList;
  }

  // 使用防抖函数来处理频繁的值变化
  debounceUpdateFollowingWaypointsHeight(formattedNewVal);
};

// 截取指定小数位数而不四舍五入
const truncateToDecimalPlaces = (num, decimals) => {
  const factor = Math.pow(10, decimals);
  return (Math.trunc(num * factor) / factor).toFixed(decimals);
};

// 飞行速度
const flightspeedClick = (option) => {
  let currentSpeed =
    typeof form.autoFlightSpeed === "string"
      ? parseFloat(form.autoFlightSpeed)
      : Number(form.autoFlightSpeed);

  if (isNaN(currentSpeed)) currentSpeed = minSpeed.value;

  // 使用1作为步进值
  const change = option === "-" ? -1 : option === "+" ? 1 : 0;

  // 计算新值并确保在范围内
  let newSpeed = currentSpeed + change;
  newSpeed = Math.max(minSpeed.value, Math.min(maxflightspeed.value, newSpeed));

  // 保留一位小数
  const formattedNewSpeed = parseFloat(newSpeed.toFixed(1));
  form.autoFlightSpeed = formattedNewSpeed;

  // 只更新勾选了"跟随航线"的航点速度
  if (airlineList.value && airlineList.value.length > 0) {
    airlineList.value.forEach((item) => {
      // 只有当航点设置为跟随航线时才更新速度
      if (item.waypointSpeedFollow === 1) {
        item.waypointSpeed = formattedNewSpeed;
      }
      // 检查未跟随航线的航点，如果速度变得与航线速度一致，则自动勾选跟随
      else if (item.waypointSpeedFollow === 0) {
        const speedDiff = Math.abs(item.waypointSpeed - formattedNewSpeed);
        if (speedDiff < 0.01) {
          item.waypointSpeedFollow = 1;
        }
      }
    });
    // 强制触发响应式更新
    airlineList.value = [...airlineList.value];
  }

  // 添加防抖自动保存
  // debouncedAutoSave();
};
// 起飞速度
const takeoffspeedClick = (option) => {
  if (typeof form.globalTransitionalSpeed == "string") {
    form.globalTransitionalSpeed = parseFloat(form.globalTransitionalSpeed);
  }
  // 确保当前值在有效范围内
  if (
    isNaN(form.globalTransitionalSpeed) ||
    form.globalTransitionalSpeed < minSpeed.value
  ) {
    form.globalTransitionalSpeed = minSpeed.value;
  } else if (form.globalTransitionalSpeed > maxflightspeed.value) {
    form.globalTransitionalSpeed = maxflightspeed.value;
  }

  const change =
    {
      "-": -1,
      "+": 1,
    }[option] || 0;

  form.globalTransitionalSpeed = adjustValue(
    form.globalTransitionalSpeed,
    change,
    minSpeed.value, // 使用速度最小值
    maxflightspeed.value
  );

  // 添加防抖自动保存
  // debouncedAutoSave();
};
//安全起飞高度
const safetakeoffaltitudeClick = (option) => {
  let currentHeight =
    typeof form.takeOffSecurityHeight === "string"
      ? parseFloat(form.takeOffSecurityHeight)
      : Number(form.takeOffSecurityHeight);

  if (isNaN(currentHeight)) currentHeight = 1;

  // 使用1作为步进值
  const change = option === "-" ? -1 : option === "+" ? 1 : 0;

  // 计算新值并确保在范围内
  let newHeight = currentHeight + change;
  newHeight = Math.max(1, Math.min(500, newHeight));

  // 保留一位小数
  form.takeOffSecurityHeight = parseFloat(newHeight.toFixed(1));

  // 添加防抖自动保存
  // debouncedAutoSave();
};
//返航高度
const returnaltitudeClick = (option) => {
  let currentHeight =
    typeof form.globalRTHHeight === "string"
      ? parseFloat(form.globalRTHHeight)
      : Number(form.globalRTHHeight);

  if (isNaN(currentHeight)) currentHeight = 1;

  // 使用1作为步进值
  const change = option === "-" ? -1 : option === "+" ? 1 : 0;

  // 计算新值并确保在范围内
  let newHeight = currentHeight + change;
  newHeight = Math.max(1, Math.min(500, newHeight));

  // 保留一位小数
  form.globalRTHHeight = parseFloat(newHeight.toFixed(1));

  // 添加防抖自动保存
  // debouncedAutoSave();
};
// // 无人机失控
// const destinationtypeClick = (option) => {
//   if (option == '-') {
//     if (form.destinationtype < max.value) {
//       form.destinationtype -= 1;
//     }
//   }
// };

// 飞行高度
const yawaltitudeClick = (option) => {
  let currentHeight =
    typeof formyaw.height === "string"
      ? parseFloat(formyaw.height)
      : Number(formyaw.height);

  if (isNaN(currentHeight)) currentHeight = min.value;

  // 使用1作为步进值
  const change = option === "-" ? -1 : option === "+" ? 1 : 0;

  // 计算新值并确保在范围内
  let newHeight = currentHeight + change;
  newHeight = Math.max(min.value, Math.min(max.value, newHeight));

  // 保留一位小数
  formyaw.height = parseFloat(newHeight.toFixed(1));

  // 更新跟随状态（使用精度比较）
  const heightDiff = Math.abs(formyaw.height - form.globalHeight);
  formyaw.heightFollow = heightDiff < 0.01 ? 1 : 0;
  airlineList.value[waypointIndex.value].height = formyaw.height;
  airlineList.value[waypointIndex.value].heightFollow = formyaw.heightFollow;

  // 强制触发响应式更新，确保地图组件能监听到变化
  airlineList.value = [...airlineList.value];

  // 添加自动保存
  saveline();
};
// 飞行速度
const yawspeedClick = (option) => {
  // 确保 formyaw.flightspeed 是数字类型
  let currentSpeed = Number(formyaw.flightspeed);
  if (isNaN(currentSpeed)) currentSpeed = 0;

  // 使用1作为步进值
  const change = option === "-" ? -1 : option === "+" ? 1 : 0;

  // 计算新值并确保在范围内
  let newSpeed = currentSpeed + change;
  newSpeed = Math.max(0, Math.min(maxflightspeed.value, newSpeed));

  // 保留一位小数
  formyaw.flightspeed = parseFloat(newSpeed.toFixed(1));

  // 更新跟随状态（使用精度比较）
  const speedDiff = Math.abs(formyaw.flightspeed - form.autoFlightSpeed);
  formyaw.waypointSpeedFollow = speedDiff < 0.01 ? 1 : 0;

  airlineList.value[waypointIndex.value].waypointSpeed = Number(
    formyaw.flightspeed
  );
  airlineList.value[waypointIndex.value].waypointSpeedFollow =
    formyaw.waypointSpeedFollow;

  // 触发changeFlightSpeed来同步其他状态
  changeFlightSpeed(formyaw.flightspeed);
};
// 加减动作
const actionValueClick = (item, option) => {
  // 确保actionValue是数字类型
  item.actionValue = Number(item.actionValue);
  item.actionMin = Number(item.actionMin);
  item.actionMax = Number(item.actionMax);

  // 根据actionType确定精度
  const needDecimal = [2, 3, 7, 9].includes(item.actionType);
  const step = 1;

  if (option === "-") {
    let newValue = item.actionValue - step;

    // 特殊处理：当 actionType 为 9 且值为 1 时，点击减号应该设置为默认值 10
    if (item.actionType === 9 && newValue < item.actionMin) {
      item.actionValue = 10;
    }
    // 对于其他 actionType，按正常逻辑处理
    else if (newValue < item.actionMin) {
      switch (item.actionType) {
        case 2: // 无人机偏航角
        case 3: // 云台俯仰角
          item.actionValue = 0;
          break;
        case 7: // 相机变焦
          item.actionValue = 2;
          break;
        default:
          item.actionValue = item.actionMin;
      }
    } else {
      item.actionValue = needDecimal
        ? parseFloat(newValue.toFixed(1))
        : Math.round(newValue);
    }
  } else {
    let newValue = item.actionValue + step;
    newValue = Math.min(item.actionMax, newValue);
    item.actionValue = needDecimal
      ? parseFloat(newValue.toFixed(1))
      : Math.round(newValue);
  }

  // 添加自动保存
  saveline();
};
// 新增更新动作值函数
const updateActionValue = (item, val) => {
  const needDecimal = [2, 3, 7, 9].includes(item.actionType);
  const numVal = Number(val);

  // 处理空值或无效值
  if (
    isNaN(numVal) ||
    numVal === null ||
    numVal === undefined ||
    numVal === ""
  ) {
    // 根据 actionType 设置不同的默认值
    switch (item.actionType) {
      case 2: // 无人机偏航角
      case 3: // 云台俯仰角
        item.actionValue = 0;
        break;
      case 7: // 相机变焦
        item.actionValue = 2;
        break;
      case 9: // 开始等距间隔拍照
        item.actionValue = 10; // 明确设置为10
        break;
      default:
        item.actionValue = needDecimal ? 0.0 : 0;
    }
  } else {
    // 确保值在有效范围内
    let clampedValue = Math.max(
      item.actionMin,
      Math.min(item.actionMax, numVal)
    );
    item.actionValue = needDecimal
      ? parseFloat(clampedValue.toFixed(1))
      : Math.round(clampedValue);
  }
  // autoSave();
  // 触发防抖自动保存
  // debouncedAutoSave();
};

const handleActionValueBlur = (item, event) => {
  const value = Number(item.actionValue);

  // 检查是否为空值或无效值
  if (
    isNaN(value) ||
    item.actionValue === null ||
    item.actionValue === undefined ||
    item.actionValue === ""
  ) {
    // 根据 actionType 设置不同的默认值
    switch (item.actionType) {
      case 2: // 无人机偏航角
      case 3: // 云台俯仰角
        item.actionValue = 0;
        break;
      case 7: // 相机变焦
        item.actionValue = 2;
        break;
      case 9: // 开始等距间隔拍照
        item.actionValue = 10; // 确保这里设置为10
        break;
      default:
        item.actionValue = 0;
    }

    // 触发更新以确保视图同步
    updateActionValue(item, item.actionValue);
  }
};

// 新增格式化滑块提示函数
const formatActionValueTooltip = (item, val) => {
  const needDecimal = [2, 3, 7, 9].includes(item.actionType);

  // 处理空值情况
  if (val === null || val === undefined || val === "") {
    switch (item.actionType) {
      case 2: // 无人机偏航角
      case 3: // 云台俯仰角
        return "0";
      case 7: // 相机变焦
        return "2";
      case 9: // 开始等距间隔拍照
        return "10";
      default:
        return needDecimal ? "0.0" : "0";
    }
  }

  return needDecimal ? `${parseFloat(val).toFixed(1)}` : Math.round(val);
};

// 跟随高度
const linealtitudeClick = (val) => {
  if (val == 1) {
    // 设置为跟随航线
    formyaw.height = form.globalHeight;
    // 更新航点数据
    airlineList.value[waypointIndex.value].height = form.globalHeight;
    airlineList.value[waypointIndex.value].heightFollow = 1;
  } else {
    // 取消跟随航线，保持当前高度不变
    // 检查defaultList是否存在且有对应索引的数据
    if (router.currentRoute.value.query.id &&
      defaultList.value &&
      defaultList.value[waypointIndex.value] !== undefined) {
      formyaw.height = defaultList.value[waypointIndex.value].height;
      // 更新航点数据
      airlineList.value[waypointIndex.value].height = defaultList.value[waypointIndex.value].height;
    } else {
      // 对于新创建的航点，使用当前高度值
      formyaw.height = airlineList.value[waypointIndex.value].height;
    }
    // 设置为不跟随
    airlineList.value[waypointIndex.value].heightFollow = 0;
  }
  formyaw.heightFollow = val;
  // 强制触发响应式更新，确保地图组件能监听到变化
  airlineList.value = [...airlineList.value];

  // 触发自动保存
  // autoSave();
};

// 处理输入框失去焦点事件
const handleBlur = (e, field) => {
  if (field === "globalHeight") {
    // 确保保留一位小数
    let value = parseFloat(e.target.value);

    // 如果值为空或无效，设置为最小值0.0
    if (isNaN(value) || e.target.value === "" || e.target.value === null) {
      value = 0.0;
    } else {
      // 限制在范围内并保留一位小数
      value = Math.max(min.value, Math.min(max.value, value));
    }

    const newHeight = parseFloat(value.toFixed(1));
    form.globalHeight = newHeight;

    // 只更新勾选了"跟随航线"的航点高度
    if (airlineList.value && airlineList.value.length > 0) {
      const updatedList = airlineList.value.map((item, index) => {
        // 创建新对象确保响应式更新，同时保留所有属性
        const newItem = {
          ...item,
          height: item.heightFollow === 1 ? newHeight : item.height
        };

        // 检查未跟随航线的航点，如果高度变得与航线高度一致，则自动勾选跟随
        if (item.heightFollow === 0) {
          const heightDiff = Math.abs(item.height - newHeight);
          if (heightDiff < 0.01) {
            newItem.heightFollow = 1;
          }
        }

        return newItem;
      });

      // 强制触发响应式更新
      airlineList.value = updatedList;
    }
  }

  if (field === "autoFlightSpeed") {
    let value = parseFloat(e.target.value);
    // 如果值为空或无效，设置为最小值1.0
    if (isNaN(value) || e.target.value === "" || e.target.value === null) {
      value = 1.0;
    } else {
      // 确保在速度范围内并保留一位小数
      if (value < minSpeed.value) {
        value = minSpeed.value;
      } else if (value > maxflightspeed.value) {
        value = maxflightspeed.value;
      }
    }
    const newSpeed = parseFloat(value.toFixed(1));
    form.autoFlightSpeed = newSpeed;

    // 只更新勾选了"跟随航线"的航点速度
    if (airlineList.value && airlineList.value.length > 0) {
      airlineList.value.forEach((item) => {
        // 只有当航点设置为跟随航线时才更新速度
        if (item.waypointSpeedFollow === 1) {
          item.waypointSpeed = newSpeed;
        }
        // 检查未跟随航线的航点，如果速度变得与航线速度一致，则自动勾选跟随
        else if (item.waypointSpeedFollow === 0) {
          const speedDiff = Math.abs(item.waypointSpeed - newSpeed);
          if (speedDiff < 0.01) {
            item.waypointSpeedFollow = 1;
          }
        }
      });
      // 强制触发响应式更新
      airlineList.value = [...airlineList.value];
    }
  }

  if (field === "takeOffSecurityHeight") {
    let value = parseFloat(e.target.value);

    // 如果值为空或无效，设置为默认值 1
    if (isNaN(value) || e.target.value === "" || e.target.value === null) {
      value = 1;
    } else {
      // 限制在范围内并保留一位小数
      value = Math.max(1, Math.min(500, value));
    }

    form.takeOffSecurityHeight = parseFloat(value.toFixed(1));
  }
  if (field === "globalTransitionalSpeed") {
    let value = parseFloat(parseFloat(e.target.value).toFixed(1));
    // 确保在速度范围内
    if (isNaN(value) || value < minSpeed.value) {
      value = minSpeed.value;
    } else if (value > maxflightspeed.value) {
      value = maxflightspeed.value;
    }
    form.globalTransitionalSpeed = value;
  }
  if (field === "globalRTHHeight") {
    let value = parseFloat(e.target.value);

    // 如果值为空或无效，设置为默认值 1
    if (isNaN(value) || e.target.value === "" || e.target.value === null) {
      value = 1;
    } else {
      // 限制在范围内并保留一位小数
      value = Math.max(1, Math.min(500, value));
    }

    form.globalRTHHeight = parseFloat(value.toFixed(1));
  }
  if (field === "height") {
    formyaw.height = parseFloat(parseFloat(e.target.value).toFixed(1));
  }
  // autoSave();
};
// 改变航线高度
// const changeLineHeight = (val) => {
//   form.globalHeight = Number(val);
//   //循环airlineList.value 把高度跟随的值为1的高度设置为val
//   airlineList.value.forEach((item) => {
//     if (item.heightFollow == 1) {
//       item.height = Number(val);
//     }
//   });
//   // 强制触发响应式更新，确保地图组件能监听到变化
//   airlineList.value = [...airlineList.value];
// };
// 改变航线速度
// const changelineFlight = (val) => {
//   form.autoFlightSpeed = Number(val);
//   airlineList.value.forEach((item) => {
//     if (item.waypointSpeedFollow == 1) {
//       item.waypointSpeed = Number(val);
//     }
//   });
// };
const changeFlightaltitude = (val) => {
  // 处理空值情况，若清空则默认为0
  // val 可能是 null, undefined, '' (空字符串)
  if (val === null || val === undefined || val === "") {
    val = 0; // 设置默认值为0
  } else {
    // 如果 val 是字符串（理论上 v-model.number 会处理，但以防万一）
    if (typeof val === "string") {
      val = parseFloat(val);
    }
    // 确保 val 是一个有效数字，如果不是则设为0
    if (isNaN(val)) {
      val = 0;
    } else {
      // 保留一位小数
      val = parseFloat(val.toFixed(1));
    }
  }

  // 更新 formyaw.height，确保它是一个数字
  formyaw.height = val;

  // 判断是否跟随航线 - 使用精度比较
  const heightDiff = Math.abs(val - form.globalHeight);
  formyaw.heightFollow = heightDiff < 0.01 ? 1 : 0;

  // 更新 airlineList 中对应航点的数据
  if (
    airlineList.value &&
    airlineList.value[waypointIndex.value] !== undefined
  ) {
    airlineList.value[waypointIndex.value].height = val;
    airlineList.value[waypointIndex.value].heightFollow = formyaw.heightFollow;
    // 强制触发响应式更新
    airlineList.value = [...airlineList.value];
  }

  // 添加自动保存
  saveline();
};
const handleFlightaltitudeBlur = (event) => {
  // 当输入框失焦时，检查其值
  // 如果是 null, undefined, 或空字符串，则设置为 0
  if (
    formyaw.height === null ||
    formyaw.height === undefined ||
    formyaw.height === ""
  ) {
    changeFlightaltitude(0);
  }
};
// 跟随速度 飞行速度
const linespeedClick = (val) => {
  if (val == 1) {
    formyaw.flightspeed = form.autoFlightSpeed;
    // 更新航点数据
    airlineList.value[waypointIndex.value].waypointSpeed = form.autoFlightSpeed;
  } else {
    // 检查defaultList是否存在且有对应索引的数据
    if (router.currentRoute.value.query.id &&
      defaultList.value &&
      defaultList.value[waypointIndex.value] !== undefined) {
      formyaw.flightspeed = defaultList.value[waypointIndex.value].waypointSpeed;
      // 更新航点数据
      airlineList.value[waypointIndex.value].waypointSpeed = defaultList.value[waypointIndex.value].waypointSpeed;
    } else {
      // 对于新创建的航点，使用当前速度值
      formyaw.flightspeed = airlineList.value[waypointIndex.value].waypointSpeed;
    }
  }
  formyaw.waypointSpeedFollow = val;
  airlineList.value[waypointIndex.value].waypointSpeedFollow = val;
  airlineList.value[waypointIndex.value].waypointSpeed = formyaw.flightspeed;

  // 触发自动保存
  // autoSave();
};
// 高度模式
const getheightmode = (val, skipAutoSave = false) => {
  form.airlineHeightType = val;
  switch (val) {
    case 0: // 相对起飞点高度
      min.value = -1500;
      max.value = 1500;
      break;
    case 1: // 相对地面高度
      min.value = 0;
      max.value = 1500;
      break;
    case 2: // 绝对高度
      min.value = -2000;
      max.value = 10000;
      break;
    default:
      min.value = -1500;
      max.value = 1500;
  }

  // 确保当前飞行高度在新范围内
  const currentHeight = Number(form.globalHeight);
  let newHeight = currentHeight;
  if (currentHeight < min.value) {
    newHeight = form.globalHeight = min.value;
  } else if (currentHeight > max.value) {
    newHeight = form.globalHeight = max.value;
  }

  // 只更新勾选了"跟随航线"的航点高度
  if (airlineList.value && airlineList.value.length > 0) {
    const updatedList = airlineList.value.map((item, index) => {
      // 创建新对象确保响应式更新，同时保留所有属性
      const newItem = { ...item };

      // 只有当航点设置为跟随航线时才更新高度
      if (item.heightFollow === 1) {
        // 确保航点高度也在新范围内
        if (item.height < min.value) {
          newItem.height = min.value;
        } else if (item.height > max.value) {
          newItem.height = max.value;
        } else {
          newItem.height = newHeight;
        }
      }
      // 检查未跟随航线的航点，如果高度变得与航线高度一致，则自动勾选跟随
      else if (item.heightFollow === 0) {
        const heightDiff = Math.abs(item.height - newHeight);
        if (heightDiff < 0.01) {
          newItem.heightFollow = 1;
        }
      }

      return newItem;
    });

    // 强制触发响应式更新
    airlineList.value = updatedList;
  }

  // 只有在用户手动点击时才调用自动保存，onMounted时skipAutoSave为true，不调用
  if (!skipAutoSave) {
    autoSave();
  }
};



// 监听航线飞行速度变化，更新所有设置为"跟随航线"的航点速度
watch(
  () => form.autoFlightSpeed,
  (newSpeed, oldSpeed) => {
    // 确保新速度是有效数字
    const numericNewSpeed = Number(newSpeed);
    if (isNaN(numericNewSpeed)) return;

    // 遍历所有航点，更新设置为"跟随航线"的航点速度
    if (airlineList.value && airlineList.value.length > 0) {
      airlineList.value.forEach((item) => {
        // 只有当航点设置为跟随航线时才更新速度
        if (item.waypointSpeedFollow === 1) {
          item.waypointSpeed = numericNewSpeed;
        }
        // 检查航点速度是否与航线速度一致，如果不一致则取消跟随（使用精度比较）
        const speedDiff = Math.abs(item.waypointSpeed - numericNewSpeed);
        if (speedDiff >= 0.01) {
          item.waypointSpeedFollow = 0;
        }
      });
      // 强制触发响应式更新
      airlineList.value = [...airlineList.value];
    }
  }
);

// 获取航点设置
const getActiveName = (val) => {
  if (val == "2") {
    if (airlineList.value && airlineList.value.length == 0) {
      ElMessage({
        plain: true,
        message: "请先添加航点",
        type: "warning",
      });
      return;
    }
    // formyaw.flightaltitude = form.flightaltitude;
    // formyaw.flightspeed = form.flightspeed;
    //
    //循环更新airlineList.value 添加航点
    if (!router.currentRoute.value.query.id) {
      airlineList.value.forEach((item) => {
        if (item.waypointSpeedFollow == 1) {
          item.waypointSpeed = form.autoFlightSpeed;
        }
      });
    }
    getstopenroute(0);
  }
  activeName.value = val;
};
// 飞行速度
const changeFlightSpeed = (val) => {
  // 确保 val 是数字类型并保留一位小数
  let numericVal = Number(val);
  if (isNaN(numericVal)) {
    numericVal = 0;
  } else {
    // 保留一位小数并确保在有效范围内
    numericVal = Math.max(
      0,
      Math.min(maxflightspeed.value, parseFloat(numericVal.toFixed(1)))
    );
  }

  // 判断是否跟随航线 - 只有当航点速度与航线速度一致时才勾选跟随（使用精度比较）
  const speedDiff = Math.abs(numericVal - form.autoFlightSpeed);
  formyaw.waypointSpeedFollow = speedDiff < 0.01 ? 1 : 0;

  // 确保设置的是数字类型
  formyaw.flightspeed = numericVal;
  airlineList.value[waypointIndex.value].waypointSpeed = numericVal;
  airlineList.value[waypointIndex.value].waypointSpeedFollow =
    formyaw.waypointSpeedFollow;

  // 添加自动保存
  saveline();
};

// 关闭所有弹窗
const closeAllPopups = () => {
  // 关闭配置算法弹窗
  algorithmFlag.value = false;
  // 关闭配置喊话弹窗
  shoutFlag.value = false;
  // 关闭添加动作弹窗
  waypointactionFlag.value = false;
}

// 删除添加的动作
const deleteClick = (item) => {
  const index = formyaw.actions.findIndex(
    (option) => option.actionType === item.actionType
  );
  if (index !== -1) {
    formyaw.actions.splice(index, 1); // 删除找到的元素
  }
  airlineList.value[waypointIndex.value].actions = formyaw.actions;
  // airlineList.value = [...airlineList.value];

  // 添加自动保存
  // saveline();
}

// 拖拽排序结束回调函数
// const onEnd = (evt) => {
//   // 拖拽排序结束后触发防抖自动保存
//   debouncedAutoSave();
// };

// 保存航线设置函数
const saveline = async () => {
  // 将布尔值转换为API需要的格式：true -> 0(选中)，false -> 1(未选中)
  // const wideType = form.wideType ? 0 : 1; // 0代表选中，1代表未选中
  // const zoomType = form.zoomType ? 0 : 1; // 0代表选中，1代表未选中
  const irType = form.irType ? 0 : 1; // 0代表选中，1代表未选中
  const visableType = form.visableType ? 0 : 1; // 0代表选中，1代表未选中
  if (visableType == 1 && irType == 1) {
    ElMessage({
      message: "请至少选择一种照片存储类型",
      type: "warning",
    });
    return;
  }
  ElMessage({
    plain: true,
    message: "航线配置保存成功",
    type: "success",
  });
  // 关闭所有弹窗
  closeAllPopups();

  // 更新航点数据标志
  if (airlineList.value && airlineList.value.length > 0) {
    hasWaypointData.value = true;
  }

  // 如果不是初始加载，则触发防抖自动保存
  if (!isInitialLoad.value) {
    debouncedAutoSave();
  }
};
// 设置最大最小值
const actionMin = ref(0);
const actionMax = ref(0);
// 添加动作
const addClick = () => {
  // 显示动作选择界面
  waypointactionFlag.value = true;
  algorithmFlag.value = false;
  shoutFlag.value = false;
};
// 关闭添加动作
const getClose = () => {
  waypointactionFlag.value = false;
  algorithmFlag.value = false;
  shoutFlag.value = false;
};

// 算法配置
const getalgoSetting = (item) => {
  formyaw.algorithmExtends = [];
  if (item) {
    formyaw.algorithmExtends = item;
  }
  // 添加安全检查
  if (
    airlineList.value &&
    waypointIndex.value !== undefined &&
    waypointIndex.value !== null &&
    airlineList.value[waypointIndex.value]
  ) {
    airlineList.value[waypointIndex.value].algorithmExtendsByIds =
      formyaw.algorithmExtends;
  }
  saveline();
};
// 配置算法id集合
const getalgoView = (item) => {
  // 初始化算法
  formyaw.algorithm = [];
  if (item) {
    formyaw.algorithm = item;
  }
  algorithmFlag.value = false;
  // 添加安全检查
  if (
    airlineList.value &&
    waypointIndex.value !== undefined &&
    waypointIndex.value !== null &&
    airlineList.value[waypointIndex.value]
  ) {
    airlineList.value[waypointIndex.value].algorithmIds = formyaw.algorithm;
  }
};
// 配置算法
const algorithmClick = () => {
  // 添加安全检查
  if (
    airlineList.value &&
    waypointIndex.value !== undefined &&
    waypointIndex.value !== null &&
    airlineList.value[waypointIndex.value]
  ) {
    algorithmList.value = airlineList.value[waypointIndex.value].algorithmIds;
    // 新增算法配置
    formyaw.algorithmExtends =
      airlineList.value[waypointIndex.value].algorithmExtendsByIds;
  }
  algorithmConfig.value.algorithmExtends = formyaw.algorithmExtends;
  algorithmConfig.value.algorithmList = algorithmList.value;
  algorithmFlag.value = true;
  waypointactionFlag.value = false;
  shoutFlag.value = false;
};
// 添加配置喊话
const getShoutview = (item) => {
  formyaw.shout = {
    // megaphoneOperateLoop:formyaw.shout.mode,
    // megaphoneType:formyaw.shout.megaphoneType,
    // megaphoneOperateFile:formyaw.shout.entercontent,
    // text:formyaw.shout.writecontent,
    // playVolume:formyaw.shout.volume,
  };
  if (item) {
    formyaw.shout = item;
  }
  shoutFlag.value = false;
  // 添加安全检查
  if (
    airlineList.value &&
    waypointIndex.value !== undefined &&
    waypointIndex.value !== null &&
    airlineList.value[waypointIndex.value]
  ) {
    airlineList.value[waypointIndex.value].megaphoneOperate = formyaw.shout;
  }

  saveline();
};
// 配置喊话
const shoutClick = () => {
  // 添加安全检查
  if (
    airlineList.value &&
    waypointIndex.value !== undefined &&
    waypointIndex.value !== null &&
    airlineList.value[waypointIndex.value] &&
    airlineList.value[waypointIndex.value].megaphoneOperate
  ) {
    shoutList.value = airlineList.value[waypointIndex.value].megaphoneOperate;
  } else {
    // 如果没有现有的喊话配置，初始化一个空对象
    shoutList.value = {
      mode: 0,
      volume: 0,
      writecontent: "",
      entercontent: "",
      megaphoneType: "0",
    };
  }
  shoutFlag.value = true;
  waypointactionFlag.value = false;
  algorithmFlag.value = false;
};
// 添加动作
const getwayView = (item) => {
  if (item) {
    // 确保每个动作都有正确的最大最小值和唯一ID
    let processedActions = item.map((action, actionIndex) => {
      const baseAction = {
        ...action,
        id: action.id || `action_${Date.now()}_${actionIndex}`, // 添加唯一ID
        // 确保actionValue是数字类型
        actionValue: Number(action.actionValue),
      };

      switch (action.actionType) {
        case 1: // 悬停
          return { ...baseAction, actionMin: 1, actionMax: 900 };
        case 2: // 无人机偏航角
          return { ...baseAction, actionMin: -180, actionMax: 180 };
        case 3: // 云台俯仰角
          return { ...baseAction, actionMin: -120, actionMax: 45 };
        case 7: // 相机变焦
          return { ...baseAction, actionMin: 2, actionMax: 200 };
        case 9: // 开始等距间隔拍照
          return { ...baseAction, actionMin: 1, actionMax: 900 };
        case 10: // 开始等时间隔拍照
          return { ...baseAction, actionMin: 1, actionMax: 30 };
        default:
          return baseAction;
      }
    });
    formyaw.actions = processedActions;
  }
  algorithmFlag.value = false;
  // 添加安全检查
  if (
    airlineList.value &&
    waypointIndex.value !== undefined &&
    waypointIndex.value !== null &&
    airlineList.value[waypointIndex.value]
  ) {
    airlineList.value[waypointIndex.value].actions = formyaw.actions;
  }

  // 当航点动作更新时，重新计算飞行时长
  if (
    airlineList.value &&
    airlineList.value.length > 0 &&
    distanceArray.value &&
    distanceArray.value.length > 0
  ) {
    getflighttime(airlineList.value);
  }

  // 使用nextTick确保DOM更新后再初始化动作拖拽排序
  nextTick(() => {
    setTimeout(() => {
      initializeActionsSortable();
    }, 200);
  });

  saveline();
};

// 重设起飞点/取消设置
const setTakeoffMode = (val) => {
  flayShow.value = val;
  // 如果退出重设模式（val为true），重置状态
  if (val === true) {
    isResettingTakeoff.value = false;
    // 使用防抖自动保存优化起飞点设置的保存调用
    debouncedAutoSave();
  }
};
// 首次设置
const oneSetTakeoffMode = (val) => {
  flayoneShow.value = val;
  // 更新起飞点标志
  hasTakeoffPoint.value = !val; // false表示已设置起飞点，true表示未设置

  // 如果起飞点已设置且不是初始加载，则触发防抖自动保存
  if (!val && !isInitialLoad.value) {
    debouncedAutoSave();
  }
};

// 进入重设起飞点模式
const enterResetTakeoffMode = () => {
  isResettingTakeoff.value = true;
  flayShow.value = false; // 设置为false进入重设模式
  // 通知地图组件进入重设模式
  if (mapRef.value) {
    mapRef.value.enterSetTakeoffMode();
  }
};
// 取消重设起飞点模式
const cancelResetTakeoffMode = () => {
  isResettingTakeoff.value = false;
  flayShow.value = true; // 设置为true退出重设模式
  // 通知地图组件退出重设模式
  if (mapRef.value) {
    mapRef.value.exitSetTakeoffMode();
  }
};

// 在组件卸载前清理sortable实例
onBeforeUnmount(() => {
  if (actionsContainer.value && actionsContainer.value.sortableInstance) {
    try {
      actionsContainer.value.sortableInstance.destroy();
    } catch (e) {
      console.log("Error destroying sortable instance:", e);
    }
    actionsContainer.value.sortableInstance = null;
  }
});

// 初始化动作拖拽排序
const initializeActionsSortable = async () => {
  // 等待DOM更新完成
  await nextTick();

  // 确保容器存在
  if (actionsContainer.value) {
    // 先销毁已存在的sortable实例（如果有的话）
    if (actionsContainer.value.sortableInstance) {
      try {
        actionsContainer.value.sortableInstance.destroy();
      } catch (e) {
        console.log("Error destroying sortable instance:", e);
      }
      actionsContainer.value.sortableInstance = null;
    }

    // 检查容器中是否有子元素
    const children = actionsContainer.value.children;

    // 确保有足够的元素才初始化拖拽
    if (children.length < 1) {
      // console.log("No items for sorting, skipping initialization");
      return;
    }

    try {
      // 创建Sortable实例
      const sortable = new Sortable(actionsContainer.value, {
        animation: 150,
        ghostClass: "sortable-ghost",
        chosenClass: "sortable-chosen",
        dragClass: "sortable-drag",
        handle: ".sortable-handle", // 只在特定元素上触发拖拽
        // onStart: (evt) => {
        //   console.log("Actions at start:", JSON.stringify(formyaw.actions));
        // },
        onEnd: (evt) => {
          // 拖拽结束时更新数据
          const { oldIndex, newIndex } = evt;

          // 确保索引有效
          if (
            oldIndex !== undefined &&
            newIndex !== undefined &&
            oldIndex !== newIndex &&
            oldIndex < formyaw.actions.length &&
            newIndex < formyaw.actions.length
          ) {
            // 创建新的动作数组副本
            const newActions = [...formyaw.actions];

            // 重新排列数组
            const movedItem = newActions.splice(oldIndex, 1)[0];
            newActions.splice(newIndex, 0, movedItem);

            // 更新formyaw.actions
            formyaw.actions = newActions;

            // 更新航点动作
            if (airlineList.value && airlineList.value[waypointIndex.value]) {
              airlineList.value[waypointIndex.value].actions = [...newActions];
              // 强制触发响应式更新
              airlineList.value = [...airlineList.value];
            }

            // 添加自动保存
            saveline();
          } else {
            // console.log(
            //   "Invalid drag operation:",
            //   oldIndex,
            //   newIndex,
            //   formyaw.actions.length
            // );
          }
        },
      });

      // 保存sortable实例引用，以便后续销毁
      actionsContainer.value.sortableInstance = sortable;
      return sortable;
    } catch (error) {
      console.error("Failed to initialize Sortable:", error);
    }
  } else {
    console.log("Actions container not found");
  }
};
// 获取所有数据
const getallData = (val) => {
  allData.value = val;
  // 保存现有的航点动作数据
  const existingActions = airlineList.value
    ? airlineList.value.map((waypoint) => ({
      actions: waypoint.actions || [],
      algorithmIds: waypoint.algorithmIds || [],
      algorithmExtendsByIds: waypoint.algorithmExtendsByIds || [],
      megaphoneOperate: waypoint.megaphoneOperate || {},
      positionType: waypoint.positionType || 2,
      imageFormat: waypoint.imageFormat || 0,
      attitudeHead: waypoint.attitudeHead || 0,
      waypointSpeed: waypoint.waypointSpeed || 10,
      height: waypoint.height || 100,
      heightFollow: waypoint.heightFollow,
      waypointSpeedFollow: waypoint.waypointSpeedFollow,
    }))
    : [];
  // 添加obj所有属性
  airlineList.value = Array(val[0].points.length)
    .fill()
    .map((_, index) => {
      // 使用深拷贝确保每个对象都是独立的
      const newObj = {
        ...JSON.parse(JSON.stringify(obj)),
        index, // 添加索引属性
      };
      // 设置航点名称为"航点"加上索引值加1
      newObj.wayPointName = `航点${index + 1}`;
      if (index < val[0].points.length) {
        newObj.longitude = val[0].points[index][0]; // 经度
        newObj.latitude = val[0].points[index][1]; // 纬度
        newObj.height = val[0].points[index][2]; // 高度
      }

      // 保留现有的动作数据（如果存在）
      if (existingActions[index]) {
        newObj.actions = existingActions[index].actions;
        newObj.algorithmIds = existingActions[index].algorithmIds;
        newObj.algorithmExtendsByIds =
          existingActions[index].algorithmExtendsByIds;
        newObj.megaphoneOperate = existingActions[index].megaphoneOperate;
        newObj.positionType = existingActions[index].positionType;
        newObj.imageFormat = existingActions[index].imageFormat;
        newObj.attitudeHead = existingActions[index].attitudeHead;
        newObj.waypointSpeed = existingActions[index].waypointSpeed;
        newObj.heightFollow = existingActions[index].heightFollow;
        newObj.waypointSpeedFollow = existingActions[index].waypointSpeedFollow;
      } else {
        // 对于新添加的航点，根据当前值与航线设置值是否相等来判断是否跟随（使用精度比较）
        const heightDiff = Math.abs(newObj.height - form.globalHeight);
        const speedDiff = Math.abs(newObj.waypointSpeed - form.autoFlightSpeed);
        newObj.heightFollow = heightDiff < 0.01 ? 1 : 0;
        newObj.waypointSpeedFollow = speedDiff < 0.01 ? 1 : 0;
      }

      return newObj;
    });

  // 更新航点数据标志
  hasWaypointData.value = airlineList.value && airlineList.value.length > 0;

  // 当航点数据更新时，重新计算飞行时长
  if (
    airlineList.value &&
    airlineList.value.length > 0 &&
    distanceArray.value &&
    distanceArray.value.length > 0
  ) {
    getflighttime(airlineList.value);
  }

  // 如果defaultList.value有值，则赋值给airlineList.value
  if (
    defaultList.value &&
    defaultList.value.length > 0 &&
    defaultList.value.length >= airlineList.value.length
  ) {
    //  defaultList waypointSpeed attitudeHead赋值给airlineList.value
    airlineList.value.forEach((item) => {
      item.attitudeHead = defaultList.value[item.index].attitudeHead; // 偏航角
      item.imageFormat = defaultList.value[item.index].imageFormat; // 镜头模式
      item.waypointSpeed = defaultList.value[item.index].waypointSpeed; // 速度
      item.heightFollow = defaultList.value[item.index].heightFollow; // 跟随航线高度
      item.positionType = defaultList.value[item.index].positionType; // 地图
      item.actions = defaultList.value[item.index].actions; // 动作
      item.waypointSpeedFollow =
        defaultList.value[item.index].waypointSpeedFollow; // 跟随航线速度
    });
  } else {
    // 获取最后一个航点的索引
    const lastIndex = airlineList.value.length - 1;
    if (lastIndex >= 0) {
      // 修改最后一个航点的参数
      // 根据高度和速度是否相等设置跟随状态（使用精度比较）
      const heightDiff = Math.abs(airlineList.value[lastIndex].height - form.globalHeight);
      const speedDiff = Math.abs(airlineList.value[lastIndex].waypointSpeed - form.autoFlightSpeed);

      airlineList.value[lastIndex] = {
        ...airlineList.value[lastIndex],
        attitudeHead: 0, // 偏航角
        imageFormat: 0, // 镜头模式
        waypointSpeed: form.autoFlightSpeed, // 速度
        heightFollow: heightDiff < 0.01 ? 1 : 0, // 跟随航线高度
        positionType: 2, // 地图
        waypointSpeedFollow: speedDiff < 0.01 ? 1 : 0, // 跟随航线速度
      };
    }
  }

  //保留默认高德数据
  gaodeList.value = airlineList.value.map((item) => ({
    longitude: item.longitude,
    latitude: item.latitude,
  }));
  showDataloading.value = true; //刷新状态
  if (activeName.value == "2") {
    if (airlineList.value && airlineList.value.length > 0) {
      getstopenroute(0);
    } else {
      activeName.value = "1";
    }
  }
  setTimeout(() => {
    showDataloading.value = false; //刷新状态
    // 当航点数据更新时，重新初始化拖拽功能
    if (
      activeName.value == "2" &&
      airlineList.value &&
      airlineList.value.length > 0
    ) {
      nextTick(() => {
        setTimeout(() => {
          initializeActionsSortable();
        }, 200);
      });
    }
  }, 300);

  // 如果不是初始加载且有航点数据，则触发防抖自动保存（优化：只调用一次）
  // if (!isInitialLoad.value && hasWaypointData.value) {
  //   debouncedAutoSave();
  // }
};
// 获取总距离
const gettotalDistance = (val) => {
  formyaw.totalDistance = val;
};
// 获取航点名称
const getstopenroute = async (val) => {
  showDataloading.value = true; //刷新状态
  airlineClick(val); //更新右边选中
  waypointIndex.value = val;
  formyaw.longitude = airlineList.value[waypointIndex.value].longitude;
  formyaw.latitude = airlineList.value[waypointIndex.value].latitude;
  formyaw.positionType = airlineList.value[waypointIndex.value].positionType;
  formyaw.imageFormat = airlineList.value[waypointIndex.value].imageFormat;
  formyaw.attitudeHead = airlineList.value[waypointIndex.value].attitudeHead;

  // 根据当前航点值与航线设置值是否相等来设置跟随状态（使用精度比较）
  const heightDiff = Math.abs(airlineList.value[waypointIndex.value].height - form.globalHeight);
  const speedDiff = Math.abs(airlineList.value[waypointIndex.value].waypointSpeed - form.autoFlightSpeed);
  formyaw.heightFollow = heightDiff < 0.01 ? 1 : 0;
  formyaw.waypointSpeedFollow = speedDiff < 0.01 ? 1 : 0;

  // 处理动作数据，确保有正确的最大最小值
  const actions = airlineList.value[waypointIndex.value].actions;
  if (actions && Array.isArray(actions)) {
    // 如果有动作数据，处理最大最小值
    const processedActions = actions.map((action) => {
      // 确保actionValue是数字类型并保留一位小数（如果需要）
      const needDecimal = [2, 3, 7, 9].includes(action.actionType);
      const processedAction = {
        ...action,
        actionValue: needDecimal
          ? parseFloat(truncateToDecimalPlaces(Number(action.actionValue), 1))
          : Number(action.actionValue),
        actionMin: Number(action.actionMin),
        actionMax: Number(action.actionMax),
      };

      switch (action.actionType) {
        case 1: // 悬停
          return { ...processedAction, actionMin: 1, actionMax: 900 };
        case 2: // 无人机偏航角
          return { ...processedAction, actionMin: -180, actionMax: 180 };
        case 3: // 云台俯仰角
          return { ...processedAction, actionMin: -120, actionMax: 45 };
        case 7: // 相机变焦
          return { ...processedAction, actionMin: 2, actionMax: 200 };
        case 9: // 开始等距间隔拍照
          return { ...processedAction, actionMin: 1, actionMax: 900 };
        case 10: // 开始等时间隔拍照
          return { ...processedAction, actionMin: 1, actionMax: 30 };
        default:
          return processedAction;
      }
    });
    formyaw.actions = processedActions;
  } else {
    formyaw.actions = [];
    // 将空动作数组保存到航点数据中
    airlineList.value[waypointIndex.value].actions = [];
  }
  formyaw.flightspeed = airlineList.value[waypointIndex.value].waypointSpeed;
  formyaw.height = airlineList.value[waypointIndex.value].height;
  formyaw.algorithm = airlineList.value[waypointIndex.value].algorithmIds;
  formyaw.shout = airlineList.value[waypointIndex.value].megaphoneOperate;
  formyaw.algorithmExtends =
    airlineList.value[waypointIndex.value].algorithmExtendsByIds;

  // 编辑的时候
  if (router.currentRoute.value.query.id) {
    if (formyaw.positionType !== 2) {
      const option = await coordinateData({
        longitude: gaodeList.value[waypointIndex.value].longitude,
        latitude: gaodeList.value[waypointIndex.value].latitude,
        method: "wgs84ToGcj02",
      });
      formyaw.longitude = parseFloat(option.longitude.toFixed(12));
      formyaw.latitude = parseFloat(option.latitude.toFixed(12));
    } else {
      formyaw.longitude = gaodeList.value[waypointIndex.value].longitude;
      formyaw.latitude = gaodeList.value[waypointIndex.value].latitude;
    }
  }

  setTimeout(() => {
    showDataloading.value = false; //刷新状态
    // 使用nextTick确保DOM更新后再初始化动作拖拽排序
    nextTick(() => {
      setTimeout(() => {
        initializeActionsSortable();
      }, 200);
    });
  }, 300);
};

const getWayPointName = (index) => {
  const wayPoint = airlineList.value.find((item) => item.index === index);
  return wayPoint ? wayPoint.wayPointName : "";
};

// 保存航点设置
const saveList = () => {
  const wayPointName = getWayPointName(formyaw.wayPointName);
  if (!wayPointName) {
    ElMessage({
      plain: true,
      message: "请先添加航点",
      type: "warning",
    });
    return;
  }
  try {
    // 检查airlineList和waypointIndex是否有效
    if (
      !airlineList.value ||
      !Array.isArray(airlineList.value) ||
      waypointIndex.value === undefined ||
      waypointIndex.value === null
    ) {
      console.error("无效的参数:", {
        airlineList: airlineList.value,
        waypointIndex: waypointIndex.value,
      });
      return;
    }

    // 检查索引是否在有效范围内
    if (
      waypointIndex.value < 0 ||
      waypointIndex.value >= airlineList.value.length
    ) {
      console.error("索引超出范围:", waypointIndex.value);
      return;
    }

    // 获取当前航点对象
    const currentWaypoint = airlineList.value[waypointIndex.value];
    if (!currentWaypoint) {
      console.error("航点对象不存在:", waypointIndex.value);
      return;
    }

    // 更新航点属性
    currentWaypoint.positionType = formyaw.positionType;
    currentWaypoint.waypointSpeed = formyaw.flightspeed;
    currentWaypoint.imageFormat = formyaw.imageFormat;
    currentWaypoint.attitudeHead = formyaw.attitudeHead;
    currentWaypoint.heightFollow = formyaw.heightFollow;
    currentWaypoint.waypointSpeedFollow = formyaw.waypointSpeedFollow;
    currentWaypoint.algorithmIds = formyaw.algorithm
      ? [...formyaw.algorithm]
      : [];
    currentWaypoint.algorithmExtends = formyaw.algorithmExtends
      ? [...formyaw.algorithmExtends]
      : [];
    // 安全处理actions数组
    currentWaypoint.actions = formyaw.actions ? [...formyaw.actions] : [];

    // 处理megaphoneOperate对象
    if (formyaw.shout && typeof formyaw.shout === "object") {
      currentWaypoint.megaphoneOperate.megaphoneOperateLoop =
        formyaw.shout.megaphoneOperateLoop;
      currentWaypoint.megaphoneOperate.megaphoneType =
        formyaw.shout.megaphoneType;
      currentWaypoint.megaphoneOperate.megaphoneOperateFile =
        formyaw.shout.megaphoneOperateFile;
      currentWaypoint.megaphoneOperate.text = formyaw.shout.text;
      currentWaypoint.megaphoneOperate.playVolume = formyaw.shout.playVolume;
    }
    // 飞行时长
    getflighttime(airlineList.value);
  } catch (error) {
    console.error("保存航点数据时出错:", error);
  }
  defaultList.value = JSON.parse(JSON.stringify(airlineList.value));
  // console.log(airlineList.value, "保存某个航点");
  ElMessage({
    plain: true,
    message: wayPointName + "保存成功",
    type: "success",
  });
  // 关闭所有弹窗
  closeAllPopups();

  // 使用nextTick确保DOM更新后再初始化拖拽功能
  nextTick(() => {
    setTimeout(() => {
      initializeActionsSortable();
    }, 200);
  });
  // 使用防抖自动保存优化航点保存调用
  debouncedAutoSave();
};

// 添加一个专门用于直播镜头模式变更的函数
const updateImageFormat = () => {
  // 更新航点数据
  if (airlineList.value && airlineList.value[waypointIndex.value]) {
    airlineList.value[waypointIndex.value].imageFormat = formyaw.imageFormat;
  }

  saveline();
};

// 保存数据
const updatemap = async () => {
  let method = "";
  if (formyaw.positionType == 0) {
    method = "gcj02ToWgs84";
  } else if (formyaw.positionType == 1) {
    method = "gcj02ToBd09";
  } else if (formyaw.positionType == 3) {
    method = "gcj02ToCgcs2000";
  } else {
    method = "";
  }
  airlineList.value[waypointIndex.value].positionType = formyaw.positionType;
  if (formyaw.positionType !== 2) {
    //更改坐标
    try {
      const option = await coordinateData({
        longitude: gaodeList.value[waypointIndex.value].longitude,
        latitude: gaodeList.value[waypointIndex.value].latitude,
        method: method,
      });
      formyaw.longitude = option.longitude.toFixed(12);
      formyaw.latitude = option.latitude.toFixed(12);
      //更新经纬度
      airlineList.value.forEach((item) => {
        item.longitude = Number(option.longitude.toFixed(12));
        item.latitude = Number(option.latitude.toFixed(12));
      });
    } catch (error) {
      console.error("坐标转换失败:", error);
    }
  } else {
    formyaw.longitude = gaodeList.value[waypointIndex.value].longitude;
    formyaw.latitude = gaodeList.value[waypointIndex.value].latitude;
    //更新经纬度
    airlineList.value.forEach((item) => {
      item.longitude = gaodeList.value[waypointIndex.value].longitude;
      item.latitude = gaodeList.value[waypointIndex.value].latitude;
    });
  }

  saveline();
};

// 保存编辑的航线名称
const saveAirlineNameEdit = async () => {
  try {
    const params = {
      id: router.currentRoute.value.query.id,
      airlineName: ruleForm.airlineNameData,
      airlineType: router.currentRoute.value.query.airlineType,
      brandId: form.brandId,
      seriesId: form.seriesId,
      modelId: form.modelId,
    };

    const response = await editName(params);

    // 检查响应状态
    if (response.code === 200) {
      ElMessage.success("航线名称保存成功");
    } else {
      // 接口返回业务错误
      const errorMsg = response.message || response.msg || "保存失败";
      ElMessage.error(errorMsg);
    }
  } catch (err) {
    // 处理HTTP错误
    if (err.response) {
      const { status, data } = err.response;
      let errorMsg = "操作失败";

      if (status === 500) {
        errorMsg = data?.message || data?.msg || "服务器内部错误";
      } else if (status === 404) {
        errorMsg = "接口不存在";
      } else if (status === 403) {
        errorMsg = "权限不足";
      } else if (status === 401) {
        errorMsg = "未授权访问";
      } else {
        errorMsg = data?.message || data?.msg || `请求失败 (${status})`;
      }

      ElMessage.error(errorMsg);
    } else if (err.request) {
      // 网络错误
      ElMessage.error("网络连接失败，请检查网络设置");
    } else {
      // 其他错误
      ElMessage.error(err.message || "操作失败");
    }
  }
};

// 保存新增的航线名称（在本地保存，实际会在保存航线时一起提交）
const saveAirlineNameAdd = async () => {
  try {
    const params = {
      airlineName: ruleForm.airlineNameData,
      airlineType: router.currentRoute.value.query.airlineType,
      brandId: form.brandId,
      seriesId: form.seriesId,
      modelId: form.modelId,
    };

    const response = await addName(params);

    // 检查响应状态
    if (response.code === 200) {
      ElMessage.success("航线名称保存成功");
    } else {
      // 接口返回业务错误
      const errorMsg = response.message || response.msg || "保存失败";
      ElMessage.error(errorMsg);
    }
  } catch (err) {
    // 处理HTTP错误
    if (err.response) {
      const { status, data } = err.response;
      let errorMsg = "操作失败";

      if (status === 500) {
        errorMsg = data?.message || data?.msg || "服务器内部错误";
      } else if (status === 404) {
        errorMsg = "接口不存在";
      } else if (status === 403) {
        errorMsg = "权限不足";
      } else if (status === 401) {
        errorMsg = "未授权访问";
      } else {
        errorMsg = data?.message || data?.msg || `请求失败 (${status})`;
      }

      ElMessage.error(errorMsg);
    } else if (err.request) {
      // 网络错误
      ElMessage.error("网络连接失败，请检查网络设置");
    } else {
      // 其他错误
      ElMessage.error(err.message || "操作失败");
    }
  }
};

// let wideType = 0;
// let zoomType = 0;
let irType = 0;
let visableType = 0;
const isSuccess = ref(false);
const saveAll = async () => {
  isSuccess.value = false;
  if (flayoneShow.value == true) {
    //没有设置起飞点
    ElMessage.error("请设置起飞点");
    return;
  }

  // 将布尔值转换为API需要的格式：true -> 0(选中)，false -> 1(未选中)
  // const wideType = form.wideType ? 0 : 1; // 0代表选中，1代表未选中
  // const zoomType = form.zoomType ? 0 : 1; // 0代表选中，1代表未选中
  const irType = form.irType ? 0 : 1; // 0代表选中，1代表未选中
  const visableType = form.visableType ? 0 : 1; // 0代表选中，1代表未选中
  if (visableType == 1 && irType == 1) {
    ElMessage({
      message: "请至少选择一种照片存储类型",
      type: "warning",
    });
    return;
  }

  const takeOffRefPoint =
    allData.value[0].startdata.point[0] +
    "," +
    allData.value[0].startdata.point[1];
  // 深拷贝，避免响应式对象导致的循环引用
  const wayPoints = JSON.parse(JSON.stringify(airlineList.value));
  if (gaodeList.value && gaodeList.value.length > 0) {
    const gaodeData = JSON.parse(JSON.stringify(gaodeList.value));
    wayPoints.forEach((item, index) => {
      item.longitude = gaodeData[index].longitude;
      item.latitude = gaodeData[index].latitude;

      // 如果heightFollow为undefined，则默认设置为1
      if (item.heightFollow === undefined) {
        item.heightFollow = 1;
      }

      // 如果waypointSpeedFollow为undefined，则默认设置为1
      if (item.waypointSpeedFollow === undefined) {
        item.waypointSpeedFollow = 1;
      }
    });
  }
  const time = formattedTotalTime.value;
  const params = {
    airlineName: ruleForm.airlineNameData, //form.airlineName,
    airlineType: router.currentRoute.value.query.airlineType,
    brandId: form.brandId, // 使用form中的brandId
    seriesId: form.seriesId, // 使用form中的seriesId
    modelId: form.modelId, // 使用form中的modelId
    // wideType: wideType, //广角照片
    // zoomType: zoomType, //变焦照片
    wideType: 1, //广角照片
    zoomType: 1, //变焦照片
    irType: irType, //红外照片
    visableType: visableType, //可见光照片
    airlineHeightType: form.airlineHeightType, //航线高度模式
    globalHeight: form.globalHeight, //飞行高度
    autoFlightSpeed: form.autoFlightSpeed, //飞行速度
    globalTransitionalSpeed: form.globalTransitionalSpeed, //起飞速度
    attitudeHead: form.attitudeHead, //无人机偏航角
    wayPointType: form.wayPointType, //航点类型
    outOfControlAction: form.outOfControlAction, //无人机失控动作
    finishAction: form.finishAction, //无人机完成动作
    takeOffSecurityHeight: form.takeOffSecurityHeight, //安全起飞高度
    globalRTHHeight: form.globalRTHHeight, //返航高度
    pointNum: airlineList.value.length,
    executeTime: time,
    totalDistance: formyaw.totalDistance,
    wayPoints,
    takeOffRefPoint: takeOffRefPoint,
  };

  try {
    await ruleFormRef.value?.validate();
    const response = await add(params);
    // 检查响应状态
    if (response.code === 200) {
      ElMessage.success("保存成功");
      isSuccess.value = true;
      // 关闭所有弹窗
      closeAllPopups();
      // 返回列表
      router.go(-1);
    } else {
      // 接口返回业务错误
      const errorMsg = response.message || response.msg || "保存失败";
      ElMessage.error(errorMsg);
    }
  } catch (err) {
    // 处理HTTP错误（如500、404等）
    if (err.response) {
      const { status, data } = err.response;
      let errorMsg = "操作失败";

      if (status === 500) {
        errorMsg = data?.message || data?.msg || "服务器内部错误";
      } else if (status === 404) {
        errorMsg = "接口不存在";
      } else if (status === 403) {
        errorMsg = "权限不足";
      } else if (status === 401) {
        errorMsg = "未授权访问";
      } else {
        errorMsg = data?.message || data?.msg || `请求失败 (${status})`;
      }

      ElMessage.error(errorMsg);
    } else if (err.request) {
      // 网络错误
      ElMessage.error("网络连接失败，请检查网络设置");
    } else {
      // 其他错误
      ElMessage.error(err.message || "操作失败");
    }
  }
};
const updateyaw = () => {
  airlineList.value[waypointIndex.value].attitudeHead = formyaw.attitudeHead;

  saveline();
};

// 更新航点坐标
const updateWaypointCoordinates = async () => {
  try {
    // 验证当前航点索引是否有效
    if (
      waypointIndex.value === undefined ||
      waypointIndex.value === null ||
      waypointIndex.value < 0 ||
      waypointIndex.value >= airlineList.value.length
    ) {
      console.error("无效的航点索引:", waypointIndex.value);
      return;
    }
    // 验证经纬度格式
    const longitude = parseFloat(formyaw.longitude);
    const latitude = parseFloat(formyaw.latitude);

    if (isNaN(longitude) || isNaN(latitude)) {
      console.error("经纬度格式无效");
      return;
    }
    // 验证经纬度范围
    if (longitude < -180 || longitude > 180) {
      ElMessage.error("经度范围应在-180~180之间");
      return;
    }
    if (latitude < -90 || latitude > 90) {
      ElMessage.error("纬度范围应在-90~90之间");
      return;
    }

    if (formyaw.positionType == 0) {
      //如果是84
      const option = await coordinateData({
        longitude: longitude,
        latitude: latitude,
        method: "wgs84ToGcj02",
      });
      //更新高德的数组
      gaodeList.value[waypointIndex.value].longitude = Number(
        option.longitude.toFixed(12)
      );
      gaodeList.value[waypointIndex.value].latitude = Number(
        option.latitude.toFixed(12)
      );
    } else if (formyaw.positionType == 1) {
      //如果是百度
      const option = await coordinateData({
        longitude: longitude,
        latitude: latitude,
        method: "bd09ToGcj02",
      });
      //更新高德的数组
      gaodeList.value[waypointIndex.value].longitude = Number(
        option.longitude.toFixed(12)
      );
      gaodeList.value[waypointIndex.value].latitude = Number(
        option.latitude.toFixed(12)
      );
    } else if (formyaw.positionType == 3) {
      //如果是cgcs2000
      const option = await coordinateData({
        longitude: longitude,
        latitude: latitude,
        method: "cgcs2000ToGcj02",
      });
      //更新高德的数组
      gaodeList.value[waypointIndex.value].longitude = Number(
        option.longitude.toFixed(12)
      );
      gaodeList.value[waypointIndex.value].latitude = Number(
        option.latitude.toFixed(12)
      );
    } else {
      gaodeList.value[waypointIndex.value].longitude = Number(longitude);
      gaodeList.value[waypointIndex.value].latitude = Number(latitude);
    }

    // 更新地图上的航点位置
    updateMapWaypointPosition(
      gaodeList.value[waypointIndex.value].longitude,
      gaodeList.value[waypointIndex.value].latitude
    );

    // 更新航点数据
    if (airlineList.value && airlineList.value[waypointIndex.value]) {
      airlineList.value[waypointIndex.value].longitude = gaodeList.value[waypointIndex.value].longitude;
      airlineList.value[waypointIndex.value].latitude = gaodeList.value[waypointIndex.value].latitude;
    }

    // 显示成功消息
    ElMessage.success(`航点${waypointIndex.value + 1}坐标已更新`);

    saveline();
  } catch (error) {
    console.error("更新航点坐标时出错:", error);
    ElMessage.error("更新航点坐标失败");
  }
};

// 验证坐标格式
const validateCoordinate = () => {
  const longitude = parseFloat(formyaw.longitude);
  const latitude = parseFloat(formyaw.latitude);

  // 实时验证经纬度格式
  if (
    formyaw.longitude &&
    (isNaN(longitude) || longitude < -180 || longitude > 180)
  ) {
    // 可以在这里添加实时提示
    console.warn("经度格式或范围不正确");
  }

  if (
    formyaw.latitude &&
    (isNaN(latitude) || latitude < -90 || latitude > 90)
  ) {
    // 可以在这里添加实时提示
    console.warn("纬度格式或范围不正确");
  }
};

// 更新地图上的航点位置
const updateMapWaypointPosition = (longitude, latitude) => {
  // 调用地图组件的方法更新航点位置
  if (mapRef.value && mapRef.value.updateWaypointCoordinate) {
    mapRef.value.updateWaypointCoordinate(
      waypointIndex.value,
      longitude,
      latitude
    );
  } else {
    console.warn("地图组件未初始化或方法不可用");
  }
  // 更新航点位置后触发防抖自动保存
  debouncedAutoSave();
};

// 地图组件引用
const mapRef = ref(null);
//二次确认
const savetwo = async (val) => {
  // 将布尔值转换为API需要的格式：true -> 0(选中)，false -> 1(未选中)
  // const wideType = form.wideType ? 0 : 1; // 0代表选中，1代表未选中
  // const zoomType = form.zoomType ? 0 : 1; // 0代表选中，1代表未选中
  const irType = form.irType ? 0 : 1; // 0代表选中，1代表未选中
  const visiableType = form.visiableType ? 0 : 1; // 0代表选中，1代表未选中
  if (visiableType == 1 && irType == 1) {
    ElMessage({
      message: "请至少选择一种照片存储类型",
      type: "warning",
    });
    return;
  }
  // 检查航线名称是否已填写
  if (!ruleForm.airlineNameData || ruleForm.airlineNameData.trim() === "") {
    ElMessage({
      message: "请填写航线名称",
      type: "warning",
    });
    return;
  }

  let message = "";
  if (val == "saveAllEdit" || val == "saveAll") {
    message = "是否确认保存当前数据并退出？";
  } else {
  }
  try {
    await ElMessageBox.confirm(message, "保存确认", {
      type: "success",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      beforeClose: async (action, instance, done) => {
        if (action === "confirm") {
          instance.confirmButtonLoading = true;
          try {
            if (val == "saveAllEdit") {
              saveAllEdit();
            } else {
              saveAll();
            }
            done();
          } catch (error) {
            instance.confirmButtonLoading = false;
          }
        } else {
          done();
        }
      },
    });
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error(`保存失败: ${error.message || "未知错误"}`);
      console.error("保存失败:", error);
    }
  }
};
// 自动保存航线
const autoSave = async () => {
  // 首次加载不自动保存
  if (isInitialLoad.value) {
    return;
  }

  // 根据项目规范，只有当有起飞点和航点数据时才自动保存
  // 修复：只有起飞点没有航点数据时不调用自动保存
  // 修复：删除完航点只剩下起飞点时不调用自动保存
  if (!hasTakeoffPoint.value || !hasWaypointData.value || airlineList.value.length === 0) {
    return;
  }

  // 保存中 ElLoading
  // const loadingInstance = ElLoading.service({
  //   lock: true,
  //   text: "保存中...",
  //   background: "rgba(255, 255, 255, 0.7)",
  // });
  isSuccess.value = false;

  if (flayoneShow.value == true) {
    //没有设置起飞点
    ElMessage.error("请设置起飞点");
    return;
  } else {
    // 将布尔值转换为API需要的格式：true -> 0(选中)，false -> 1(未选中)
    // const wideType = form.wideType ? 0 : 1; // 0代表选中，1代表未选中
    // const zoomType = form.zoomType ? 0 : 1; // 0代表选中，1代表未选中
    const irType = form.irType ? 0 : 1; // 0代表选中，1代表未选中
    const visiableType = form.visableType ? 0 : 1; // 0代表选中，1代表未选中
    if (visiableType == 1 && irType == 1) {
      ElMessage({
        message: "请至少选择一种照片存储类型",
        type: "warning",
      });
      return;
    }

    const takeOffRefPoint =
      allData.value[0].startdata.point[0] +
      "," +
      allData.value[0].startdata.point[1];
    // 深拷贝，避免响应式对象导致的循环引用
    const wayPoints = JSON.parse(JSON.stringify(airlineList.value));
    //处理高德的数组
    if (gaodeList.value && gaodeList.value.length > 0) {
      const gaodeData = JSON.parse(JSON.stringify(gaodeList.value));
      wayPoints.forEach((item, index) => {
        item.longitude = gaodeData[index].longitude;
        item.latitude = gaodeData[index].latitude;
      });
    }
    const time = formattedTotalTime.value;
    const params = {
      id: router.currentRoute.value.query.id,
      airlineName: ruleForm.airlineNameData, //form.airlineName,
      brandId: form.brandId, // 使用form中的brandId
      seriesId: form.seriesId, // 使用form中的seriesId
      modelId: form.modelId, // 使用form中的modelId
      // wideType: wideType,
      // zoomType: zoomType,
      wideType: 1,
      zoomType: 1,
      irType: irType,
      visiableType: visiableType,
      airlineHeightType: form.airlineHeightType,
      globalHeight: form.globalHeight,
      autoFlightSpeed: form.autoFlightSpeed,
      globalTransitionalSpeed: form.globalTransitionalSpeed,
      attitudeHead: form.attitudeHead,
      wayPointType: form.wayPointType,
      outOfControlAction: form.outOfControlAction,
      finishAction: form.finishAction,
      takeOffSecurityHeight: form.takeOffSecurityHeight,
      globalRTHHeight: form.globalRTHHeight,
      pointNum: airlineList.value.length,
      executeTime: time,
      totalDistance: formyaw.totalDistance,
      wayPoints,
      takeOffRefPoint: takeOffRefPoint,
    };

    try {
      await ruleFormRef.value?.validate();
      const response = await editAirline(params);

      // 检查响应状态
      if (response.code === 200) {
        // ElMessage.success("保存成功");
        isSuccess.value = true;
        // 关闭所有弹窗
        closeAllPopups();
      } else {
        // 接口返回业务错误
        const errorMsg = response.message || response.msg || "保存失败";
        ElMessage.error(errorMsg);
      }
    } catch (err) {
      // 处理HTTP错误（如500、404等）
      if (err.response) {
        const { status, data } = err.response;
        let errorMsg = "操作失败";

        if (status === 500) {
          errorMsg = data?.message || data?.msg || "服务器内部错误";
        } else if (status === 404) {
          errorMsg = "接口不存在";
        } else if (status === 403) {
          errorMsg = "权限不足";
        } else if (status === 401) {
          errorMsg = "未授权访问";
        } else {
          errorMsg = data?.message || data?.msg || `请求失败 (${status})`;
        }

        ElMessage.error(errorMsg);
      } else if (err.request) {
        // 网络错误
        ElMessage.error("网络连接失败，请检查网络设置");
      } else {
        // 其他错误
        ElMessage.error(err.message || "操作失败");
      }
    } finally {
      // loadingInstance.close();
    }
  }
};

// 防抖版本的自动保存函数
const debouncedAutoSave = () => {
  // 清除之前的定时器
  if (autoSaveDebounceTimer) {
    clearTimeout(autoSaveDebounceTimer);
  }

  // 设置新的防抖定时器
  autoSaveDebounceTimer = setTimeout(() => {
    autoSave();
  }, AUTO_SAVE_DEBOUNCE_DELAY);
};
const saveAllEdit = async () => {
  // 保存中 ElLoading
  const loadingInstance = ElLoading.service({
    lock: true,
    text: "保存中...",
    background: "rgba(255, 255, 255, 0.7)",
  });
  isSuccess.value = false;

  if (flayoneShow.value == true) {
    //没有设置起飞点
    ElMessage.error("请设置起飞点");
    return;
  } else {
    // 将布尔值转换为API需要的格式：true -> 0(选中)，false -> 1(未选中)
    // const wideType = form.wideType ? 0 : 1; // 0代表选中，1代表未选中
    // const zoomType = form.zoomType ? 0 : 1; // 0代表选中，1代表未选中
    const irType = form.irType ? 0 : 1; // 0代表选中，1代表未选中
    const visiableType = form.visableType ? 0 : 1; // 0代表选中，1代表未选中
    if (visiableType == 1 && irType == 1) {
      ElMessage({
        message: "请至少选择一种照片存储类型",
        type: "warning",
      });
      return;
    }

    const takeOffRefPoint =
      allData.value[0].startdata.point[0] +
      "," +
      allData.value[0].startdata.point[1];
    // 深拷贝，避免响应式对象导致的循环引用
    const wayPoints = JSON.parse(JSON.stringify(airlineList.value));
    //处理高德的数组
    if (gaodeList.value && gaodeList.value.length > 0) {
      const gaodeData = JSON.parse(JSON.stringify(gaodeList.value));
      wayPoints.forEach((item, index) => {
        item.longitude = gaodeData[index].longitude;
        item.latitude = gaodeData[index].latitude;
      });
    }
    const time = formattedTotalTime.value;
    const params = {
      id: router.currentRoute.value.query.id,
      airlineName: ruleForm.airlineNameData, //form.airlineName,
      brandId: form.brandId, // 使用form中的brandId
      seriesId: form.seriesId, // 使用form中的seriesId
      modelId: form.modelId, // 使用form中的modelId
      // wideType: wideType,
      // zoomType: zoomType,
      wideType: 1,
      zoomType: 1,
      irType: irType,
      visiableType: visiableType,
      airlineHeightType: form.airlineHeightType,
      globalHeight: form.globalHeight,
      autoFlightSpeed: form.autoFlightSpeed,
      globalTransitionalSpeed: form.globalTransitionalSpeed,
      attitudeHead: form.attitudeHead,
      wayPointType: form.wayPointType,
      outOfControlAction: form.outOfControlAction,
      finishAction: form.finishAction,
      takeOffSecurityHeight: form.takeOffSecurityHeight,
      globalRTHHeight: form.globalRTHHeight,
      pointNum: airlineList.value.length,
      executeTime: time,
      totalDistance: formyaw.totalDistance,
      wayPoints,
      takeOffRefPoint: takeOffRefPoint,
    };

    try {
      await ruleFormRef.value?.validate();
      const response = await editAirline(params);

      // 检查响应状态
      if (response.code === 200) {
        ElMessage.success("保存成功");
        isSuccess.value = true;
        // 关闭所有弹窗
        closeAllPopups();
        // 返回列表
        router.go(-1);
      } else {
        // 接口返回业务错误
        const errorMsg = response.message || response.msg || "保存失败";
        ElMessage.error(errorMsg);
      }
    } catch (err) {
      // 处理HTTP错误（如500、404等）
      if (err.response) {
        const { status, data } = err.response;
        let errorMsg = "操作失败";

        if (status === 500) {
          errorMsg = data?.message || data?.msg || "服务器内部错误";
        } else if (status === 404) {
          errorMsg = "接口不存在";
        } else if (status === 403) {
          errorMsg = "权限不足";
        } else if (status === 401) {
          errorMsg = "未授权访问";
        } else {
          errorMsg = data?.message || data?.msg || `请求失败 (${status})`;
        }

        ElMessage.error(errorMsg);
      } else if (err.request) {
        // 网络错误
        ElMessage.error("网络连接失败，请检查网络设置");
      } else {
        // 其他错误
        ElMessage.error(err.message || "操作失败");
      }
    } finally {
      loadingInstance.close();
    }
  }
};

// 详情
const getDetail = async () => {
  const params = {
    id: router.currentRoute.value.query.id,
  };
  const { data } = await getAirlineById(params);

  // 添加空值检查
  if (!data) {
    ElMessage.error("获取航线详情失败：数据为空");
    return;
  }

  // 将API返回的0/1格式转换为布尔值：0 -> true(选中)，1 -> false(未选中)
  // form.wideType = data.wideType === 0; // 0表示选中，转换为true
  // form.zoomType = data.zoomType === 0; // 0表示选中，转换为true
  form.irType = data.irType === null || data.irType === 0 ? true : false;
  form.visableType =
    data.visableType === null || data.visableType === 0 ? true : false;

  form.airlineHeightType = data.airlineHeightType || 0;
  form.autoFlightSpeed = Number(data.autoFlightSpeed) || 10;
  form.globalTransitionalSpeed = Number(data.globalTransitionalSpeed) || 10;
  form.attitudeHead = data.attitudeHead || 0;
  form.wayPointType = data.wayPointType || 1;
  form.outOfControlAction = data.outOfControlAction || 0;
  form.finishAction = data.finishAction || 0;
  form.takeOffSecurityHeight = Number(data.takeOffSecurityHeight) || 120; //安全起飞高度
  form.globalRTHHeight = Number(data.globalRTHHeight) || 120;
  formyaw.totalDistance = Number(data.totalDistance) || 0;

  // 设置品牌、系列、型号ID
  form.brandId = data.brandId;
  form.seriesId = data.seriesId;
  form.modelId = data.modelId;
  getBrand();

  // 如果有品牌ID，则加载对应的系列和型号
  if (data.brandId) {
    await getSeriesByBrandId();
  }

  drawDefaultRoute.value = convertToAllData(
    data.wayPoints,
    data.takeOffRefPoint
  );
  airlineList.value = data.wayPoints || [];
  defaultList.value = data.wayPoints || []; //保留默认数据
  gaodeList.value = data.wayPoints; //高德数组
  form.globalHeight = data.globalHeight
    ? Number(data.globalHeight)
    : airlineList.value[0]?.height
      ? Number(airlineList.value[0].height)
      : 100; //飞行高度
  // 起点
  if (data.wayPoints) {
    if (data.wayPoints.length > 0) {
      // 如果有默认航点数据，检查是否有起飞点数据
      if (data.takeOffRefPoint && data.takeOffRefPoint.trim()) {
        // 有起飞点数据，设置为已设置状态
        flayoneShow.value = false; // false表示起飞点已设置
        flayShow.value = true;
        hasTakeoffPoint.value = true; // 更新起飞点标志
      } else {
        // 没有起飞点数据，设置为未设置状态
        flayoneShow.value = true; // true表示起飞点未设置
        flayShow.value = true;
        hasTakeoffPoint.value = false; // 更新起飞点标志
      }

      // 更新航点数据标志
      hasWaypointData.value = data.wayPoints.length > 0;
    } else {
      // 没有航点数据，设置为未设置状态
      flayoneShow.value = true;
      flayShow.value = true;
      hasTakeoffPoint.value = false; // 更新起飞点标志
      hasWaypointData.value = false; // 更新航点数据标志
    }
  }

  // 初始化第一个航点的数据
  if (airlineList.value.length > 0) {
    waypointIndex.value = 0;
    const firstWaypoint = airlineList.value[0];
    formyaw.wayPointName = 0;
    formyaw.longitude = firstWaypoint.longitude;
    formyaw.latitude = firstWaypoint.latitude;
    formyaw.positionType = firstWaypoint.positionType || 2;
    formyaw.imageFormat = firstWaypoint.imageFormat || 0;
    formyaw.attitudeHead = firstWaypoint.attitudeHead || 0;

    // 高度跟随判断
    if (firstWaypoint.height === form.globalHeight) {
      formyaw.heightFollow = 1;
    } else {
      formyaw.heightFollow =
        firstWaypoint.heightFollow !== undefined
          ? firstWaypoint.heightFollow
          : 0;
    }

    // 速度跟随判断
    if (firstWaypoint.waypointSpeed === form.autoFlightSpeed) {
      formyaw.waypointSpeedFollow = 1;
    } else {
      formyaw.waypointSpeedFollow =
        firstWaypoint.waypointSpeedFollow !== undefined
          ? firstWaypoint.waypointSpeedFollow
          : 0;
    }

    formyaw.flightspeed =
      firstWaypoint.waypointSpeed !== undefined
        ? firstWaypoint.waypointSpeed
        : form.autoFlightSpeed;
    formyaw.height =
      firstWaypoint.height !== undefined
        ? firstWaypoint.height
        : form.globalHeight;
    formyaw.actions =
      firstWaypoint.actions && Array.isArray(firstWaypoint.actions)
        ? firstWaypoint.actions
        : [];
    formyaw.algorithm = firstWaypoint.algorithmIds || [];
    formyaw.shout = firstWaypoint.megaphoneOperate || {};
    formyaw.algorithmExtends = firstWaypoint.algorithmExtendsByIds || [];

    // 处理动作数据，确保有正确的最大最小值
    if (
      formyaw.actions &&
      Array.isArray(formyaw.actions) &&
      formyaw.actions.length > 0
    ) {
      formyaw.actions = formyaw.actions.map((action) => {
        switch (action.actionType) {
          case 1: // 悬停
            return { ...action, actionMin: 1, actionMax: 900 };
          case 2: // 无人机偏航角
            return { ...action, actionMin: -180, actionMax: 180 };
          case 3: // 云台俯仰角
            return { ...action, actionMin: -120, actionMax: 45 };
          case 7: // 相机变焦
            return { ...action, actionMin: 2, actionMax: 200 };
          case 9: // 开始等距间隔拍照
            return { ...action, actionMin: 1, actionMax: 900 };
          case 10: // 开始等时间隔拍照
            return { ...action, actionMin: 1, actionMax: 30 };
          default:
            return action;
        }
      });
    }
  }

  // 初始化拖拽功能
  nextTick(() => {
    if (activeName.value == "2") {
      setTimeout(() => {
        initializeActionsSortable();
      }, 100);
    }
  });

  // 数据加载完成后，设置初始加载标志为false
  isInitialLoad.value = false;
};

// 飞行时长
const getflighttime = (val) => {
  totalTime.value = 0;
  // 1. 起飞时间计算
  let takeoffTime = 0;

  if (distanceArray.value[0] && form.globalTransitionalSpeed) {
    takeoffTime = distanceArray.value[0] / form.globalTransitionalSpeed;
  }
  // 2. 起飞点到第一个航点的时间
  let takeoffToFirstWaypointTime = 0;
  if (distanceArray.value[1] && form.globalTransitionalSpeed) {
    takeoffToFirstWaypointTime =
      distanceArray.value[1] / form.globalTransitionalSpeed;
  }

  // 3. 航点间飞行时间计算
  let waypointFlightTimes = [];
  // 去掉 distanceArray 前两个，去掉 val 最后一个
  // distanceArray 从索引2开始，对应 val 从索引0开始（但要去掉最后一个）
  for (let i = 0; i < val.length - 1; i++) {
    const distanceIndex = i + 2; // distanceArray 从第三个元素开始
    const waypointItem = val[i];

    if (distanceArray.value[distanceIndex] && waypointItem.waypointSpeed) {
      const waypointTime =
        distanceArray.value[distanceIndex] / waypointItem.waypointSpeed;
      waypointFlightTimes.push({
        waypointIndex: i,
        distance: distanceArray.value[distanceIndex],
        speed: waypointItem.waypointSpeed,
        time: waypointTime,
      });
    }
  }

  // 4. 计算每个航点的悬停时间
  let hoverTimes = [];
  for (let i = 0; i < val.length; i++) {
    const waypointItem = val[i];
    let hoverTime = 0;

    // 检查该航点是否有悬停动作（actionType === 1）
    if (waypointItem.actions && Array.isArray(waypointItem.actions)) {
      const hoverAction = waypointItem.actions.find(
        (action) => action.actionType === 1
      );
      if (hoverAction && hoverAction.actionValue) {
        hoverTime = hoverAction.actionValue;
      }
    }
    hoverTimes.push({
      waypointIndex: i,
      hoverTime: hoverTime,
    });
  }
  // 5. 计算总飞行时间（包括悬停时间）
  const totalHoverTime = hoverTimes.reduce(
    (sum, item) => sum + item.hoverTime,
    0
  );
  totalTime.value =
    takeoffTime +
    takeoffToFirstWaypointTime +
    waypointFlightTimes.reduce((sum, item) => sum + item.time, 0) +
    totalHoverTime;

  return {
    takeoffTime,
    takeoffToFirstWaypointTime,
    waypointFlightTimes,
    hoverTimes,
    totalHoverTime,
  };
};
// 获取距离数组
const getdistanceArray = (val) => {
  distanceArray.value = val;
  // 当距离数组更新时，重新计算飞行时长
  if (airlineList.value && airlineList.value.length > 0) {
    getflighttime(airlineList.value);
  }
};
// 转换函数：将所有航点合并成一个 point 数组
const convertToAllData = (waypoints, takeOffRefPoint) => {
  // 安全检查：确保 waypoints 是数组
  if (!waypoints || !Array.isArray(waypoints)) {
    console.warn("convertToAllData: waypoints 不是有效的数组:", waypoints);
    waypoints = [];
  }

  const points = waypoints.map((wp) => [wp.longitude, wp.latitude, wp.height]); // 所有点

  // 处理起飞点数据 - 优先使用保存的位置信息
  let startPoint = [];
  if (form.takeoffLongitude && form.takeoffLatitude) {
    // 使用保存的起飞点位置
    startPoint = [
      form.takeoffLongitude,
      form.takeoffLatitude,
      form.takeOffSecurityHeight || 120,
    ];
  } else if (takeOffRefPoint) {
    // 如果没有保存的位置，使用传入的起飞点
    const coords = takeOffRefPoint
      .split(",")
      .map((coord) => parseFloat(coord.trim()));
    if (coords.length >= 2) {
      // 安全地获取高度，避免 points[0][2] 为空的情况
      const defaultHeight = points.length > 0 ? points[0][2] : 300;
      startPoint = [
        coords[0],
        coords[1],
        form.takeOffSecurityHeight || defaultHeight,
      ];
    }
  }

  return [
    {
      points: points, // 所有点组成的数组 - 修正字段名
      startdata: {
        point: startPoint, // 起始点
      },
    },
  ];
};
// 获取航点名称
const airlineClick = (val) => {
  const waypointData = airlineList.value.find((item) => item.index == val);
  selectedWayPoint.value = waypointData;
  getClose();
};

// 航点双击事件
const waypointDoubleClick = (waypointData) => {
  activeName.value = "2";
  formyaw.wayPointName = waypointData.index;
  getstopenroute(waypointData.index);
};
// 当开始绘制航线时，关闭重设起飞点
const getdrawingNext = (value) => {
  if (value == true) {
    isResettingTakeoff.value = false;
  }
};

// 添加此方法来处理编辑航线名称的逻辑
const editAirlineName = () => {
  // 编辑前先保存当前的航线名称，用于取消时恢复
  ruleForm.airlineNameData = form.airlineName;
  showEditAirlineName.value = true;
};

// 保存航线名称的方法
const saveAirlineName = async () => {
  // 检查航线名称是否有效
  if (!isAirlineNameValid.value) {
    ElMessage({
      type: "error",
      message: "航线名称不能为空",
    });
    return;
  }

  form.airlineName = ruleForm.airlineNameData || "";
  showEditAirlineName.value = false;

  // 根据是否有id来决定调用哪个保存接口
  if (router.currentRoute.value.query.id) {
    // 有id，调用编辑接口
    await saveAirlineNameEdit();
  } else {
    // 没有id，调用添加接口
    await saveAirlineNameAdd();
  }
};

// 取消航线名称编辑
const cancelAirlineNameEdit = () => {
  // 恢复原来的航线名称
  ruleForm.airlineNameData = form.airlineName;
  showEditAirlineName.value = false;
};

// 添加计算属性来检查航线名称是否有效（不为空且不全为空格）
const isAirlineNameValid = computed(() => {
  return ruleForm.airlineNameData && ruleForm.airlineNameData.trim() !== "";
});

// 处理回车键事件，防止换行
const handleEnter = (event) => {
  event.preventDefault();
};

// 监听选中状态变化，自动同步到 formyaw.wayPointName
watch(selectedWayPoint, (newWayPoint) => {
  if (newWayPoint && newWayPoint.index !== undefined) {
    activeName.value = "2";
    formyaw.wayPointName = newWayPoint.index;
    getstopenroute(newWayPoint.index);
    setTimeout(() => {
      showDataloading.value = false;
    }, 300);
  }
});

// 监听 formyaw.wayPointName 变化，自动同步到选中状态
watch(
  () => formyaw.wayPointName,
  (newIndex) => {
    if (newIndex !== undefined && selectedWayPoint.value?.index !== newIndex) {
      const waypointData = airlineList.value.find(
        (item) => item.index === newIndex
      );
      if (waypointData) {
        selectedWayPoint.value = waypointData;
      }
    }
  }
);

// 监听动作数组变化，重新初始化拖拽排序
watch(
  () => formyaw.actions,
  () => {
    if (
      activeName.value === "2" &&
      formyaw.actions &&
      formyaw.actions.length > 0
    ) {
      nextTick(() => {
        setTimeout(() => {
          initializeActionsSortable();
        }, 100);
      });
    }
  },
  { deep: true }
);

// 获取机场列表
const getAirportList = async () => {
  try {
    const params = {
      airportName: "",
      currentPage: "",
      pageSize: "",
    };
    const { data } = await getAirportListNoPage(params);
    if (data && data.length > 0) {
      airportList.value = data;
    } else {
      airportList.value = [];
    }
  } catch (error) {
    console.error("获取机场列表失败:", error);
    airportList.value = []; // 设置默认空数组
    ElMessage.error("获取机场列表失败");
  }
};

// 获取品牌列表
const getBrand = async () => {
  try {
    const { data } = await getBrandList();
    brandOptions.value = data || [];

    // 从路由参数中获取初始值
    const routeBrandId =
      router.currentRoute.value.query.brandId || form.brandId;
    const routeSeriesId =
      router.currentRoute.value.query.seriesId || form.seriesId;
    const routeModelId =
      router.currentRoute.value.query.modelId || form.modelId;

    // 如果路由中有品牌ID，则设置并加载对应的系列和型号
    if (routeBrandId) {
      // 检查品牌ID是否存在于品牌列表中
      const validBrand = brandOptions.value.find(
        (brand) => brand.id === routeBrandId
      );
      if (validBrand) {
        form.brandId = routeBrandId;
        await getSeriesByBrandId();

        // 如果路由中有系列ID，则设置并加载对应的型号
        if (routeSeriesId) {
          form.seriesId = routeSeriesId;
          const selectedSeries = seriesList.value.find(
            (series) => series.id === routeSeriesId
          );
          if (selectedSeries) {
            currentModels.value = selectedSeries.models || [];

            // 如果路由中有型号ID，则设置
            if (routeModelId) {
              form.modelId = routeModelId;
            } else if (
              selectedSeries.models &&
              selectedSeries.models.length > 0
            ) {
              // 默认选中第一个型号
              form.modelId = selectedSeries.models[0].id;
            }
          }
        } else if (seriesList.value && seriesList.value.length > 0) {
          // 默认选中第一个系列
          const firstSeries = seriesList.value[0];
          form.seriesId = firstSeries.id;

          // 获取第一个系列的型号列表
          currentModels.value = firstSeries.models || [];

          // 默认选中第一个型号
          if (firstSeries.models && firstSeries.models.length > 0) {
            form.modelId = firstSeries.models[0].id;
          }
        }
      } else {
        // 设置为第一个品牌（如果有）
        if (brandOptions.value.length > 0) {
          form.brandId = brandOptions.value[0].id;
          await getSeriesByBrandId();
        }
      }
    } else if (brandOptions.value.length > 0) {
      // 默认选中第一个品牌
      form.brandId = brandOptions.value[0].id;
      // 获取第一个品牌的系列列表
      await getSeriesByBrandId();
    }
  } catch (error) {
    ElMessage.error("获取品牌列表失败");
    console.error(error);
  }
};

// 监听航线飞行速度变化，更新所有设置为"跟随航线"的航点速度
const watchAutoFlightSpeed = watch(
  () => form.autoFlightSpeed,
  (newSpeed, oldSpeed) => {
    // 确保新速度是有效数字
    const numericNewSpeed = Number(newSpeed);
    if (isNaN(numericNewSpeed)) return;

    // 只更新勾选了"跟随航线"的航点速度
    if (airlineList.value && airlineList.value.length > 0) {
      airlineList.value.forEach((item) => {
        // 只有当航点设置为跟随航线时才更新速度
        if (item.waypointSpeedFollow === 1) {
          item.waypointSpeed = numericNewSpeed;
        }
        // 检查未跟随航线的航点，如果速度变得与航线速度一致，则自动勾选跟随
        else if (item.waypointSpeedFollow === 0) {
          const speedDiff = Math.abs(item.waypointSpeed - numericNewSpeed);
          if (speedDiff < 0.01) {
            item.waypointSpeedFollow = 1;
          }
        }
      });
      // 强制触发响应式更新
      airlineList.value = [...airlineList.value];
    }
  }
);

// 防抖函数，用于处理频繁的更新请求
let debounceTimer = null;
const debounceUpdateFollowingWaypointsHeight = (newHeight) => {
  // 清除之前的定时器
  if (debounceTimer) {
    clearTimeout(debounceTimer);
  }

  // 设置新的定时器
  debounceTimer = setTimeout(() => {
    updateFollowingWaypointsHeight(newHeight);
    debounceTimer = null;
  }, 100); // 100ms的防抖延迟
};

// 添加一个函数来更新所有勾选"跟随航线"的航点高度
const updateFollowingWaypointsHeight = (newHeight) => {
  // 确保新高度是有效数字
  const numericNewHeight = Number(newHeight);
  if (isNaN(numericNewHeight)) return;

  // 只更新勾选了"跟随航线"的航点高度
  if (airlineList.value && airlineList.value.length > 0) {
    const updatedList = airlineList.value.map((item, index) => {
      // 创建新对象确保响应式更新，同时保留所有属性
      const newItem = {
        ...item,
        height: item.heightFollow === 1 ? numericNewHeight : item.height
      };

      // 检查未跟随航线的航点，如果高度变得与航线高度一致，则自动勾选跟随
      if (item.heightFollow === 0) {
        const heightDiff = Math.abs(item.height - numericNewHeight);
        if (heightDiff < 0.01) {
          newItem.heightFollow = 1;
        }
      }

      return newItem;
    });

    // 强制触发响应式更新
    airlineList.value = updatedList;
  }

  // 触发自动保存
  // autoSave();
};

// 修改 watchGlobalHeight 监听器，避免重复代码
const watchGlobalHeight = watch(
  () => form.globalHeight,
  (newHeight, oldHeight) => {
    // 确保新高度是有效数字
    const numericNewHeight = Number(newHeight);
    if (isNaN(numericNewHeight)) return;

    // 只更新勾选了"跟随航线"的航点高度
    if (airlineList.value && airlineList.value.length > 0) {
      const updatedList = airlineList.value.map((item, index) => {
        // 创建新对象确保响应式更新，同时保留所有属性
        const newItem = {
          ...item,
          height: item.heightFollow === 1 ? numericNewHeight : item.height
        };

        // 检查未跟随航线的航点，如果高度变得与航线高度一致，则自动勾选跟随
        if (item.heightFollow === 0) {
          const heightDiff = Math.abs(item.height - numericNewHeight);
          if (heightDiff < 0.01) {
            newItem.heightFollow = 1;
          }
        }

        return newItem;
      });

      // 强制触发响应式更新
      airlineList.value = updatedList;
      // 只有在非初始加载状态下才触发自动保存
      // if (!isInitialLoad.value) {
      //   autoSave();
      // }
      console.log(airlineList.value, 'airlineList.value')
    }
  }
);

// 生命周期
onMounted(() => {
  getAirportList();
  // 初始化高度模式范围，onMounted时不自动保存
  getheightmode(form.airlineHeightType, true);
  // 如果是编辑模式，获取详情
  if (router.currentRoute.value.query.id) {
    getDetail();
  } else {
    getBrand();
    // 新建模式下，数据加载完成后设置初始加载标志为false
    isInitialLoad.value = false;
  }

  // ruleForm.airlineNameData = form.airlineName;
  // 初始化拖拽功能
  nextTick(() => {
    setTimeout(() => {
      initializeActionsSortable();
    }, 500);
  });
});

onBeforeUnmount(() => { });
</script>

<style scoped lang="scss">
.pageStyle {
  position: relative;
  height: calc(100vh - 88px);
  // position: relative;
  // background: #fff;
  color: #303133;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

.map-left {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1000;
  width: 17%;
  height: calc(100vh - 88px);
  padding-top: 20px;
  background: rgb(255 255 255 / 70%);
}

.airline-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 2px;

  img {
    width: 46px;
    height: 34px;
    padding: 5px 11px;
    background-color: rgb(242 242 242 / 14.9%);
    border-radius: 3px;
  }
}

.airline-header-update {
  display: flex;
  align-items: center;

  :deep(.el-input) {
    width: 80%;
  }

  p {
    width: 80%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .el-button {
    width: 20%;
  }
}

/* 添加禁用按钮的样式 */
.disabled-button {
  color: #c0c4cc !important;
  cursor: not-allowed !important;
}

.airline-distance {
  display: flex;
  padding: 10px 0;
  margin-bottom: 8px;
  text-align: center;
  background: #fff;
  border: 1px solid #dcdfe6;

  .flex-1 {
    border-right: 1px solid #e4e7ed;
  }

  .flex-1:last-child {
    border-right: none;
  }
}

.map-right {
  position: absolute;
  top: 0;
  right: 0;
  width: 17%;
  height: calc(100vh - 88px);
  background: rgb(255 255 255 / 70%);
  // overflow: scroll;

  .airline-setup {
    display: flex;
    width: 100%;
    margin: 10px 0;
    border: 1px solid #dcdfe6;

    div {
      width: 50%;
      height: 34px;
      font-size: 14px;
      line-height: 34px;
      text-align: center;
      background: #fff;
      border: 1px solid #fff;
      border-top-right-radius: 4px;
      border-bottom-right-radius: 4px;
    }

    .tab-item {
      background: #fff;
      border-right: none;
      border-radius: 4px 0 0 4px;
    }

    .tab-itemBg {
      color: #1989fa;
    }
  }

  .airline-fly {
    align-items: center;
    justify-content: space-between;
    padding: 10px;
    margin: 8px;
    background: #fff;
    border: 1px solid #dcdfe6;
    border-radius: 4px;

    img {
      width: 16px;
      height: 13px;
      margin-right: 4px;
    }

    .text {
      color: #1989fa;
    }
  }

  .airline-img {
    padding: 10px;
    margin: 8px;
    background: #fff;
    border: 1px solid #dcdfe6;
    border-radius: 4px;

    .el-checkbox {
      margin-top: 5px;
      font-size: 14px;
      font-weight: normal;
      color: #303133;
    }

    .btn {
      display: flex;
      flex-wrap: wrap;
      justify-content: flex-start;
      margin-top: 10px;
      font-size: 12px;

      p {
        // flex: 1;
        height: 32px;
        line-height: 32px;
        text-align: center;
        background-color: rgb(242 242 242 / 14.9%);
        border: 1px solid #dcdfe6;
        border-radius: 4px;

        span {
          padding: 0 6px;
        }
      }

      p:first-child {
        margin: 0 8px 8px 0;
      }

      .activeBtn {
        color: #1989fa;
        border: 1px solid #1989fa;
        // background-color: rgb(0 204 255 / 20.8%);
      }
    }

    .select {
      width: 100%;
      margin-top: 10px;

      :deep(.el-select__wrapper) {
        color: #303133;
        background: transparent;
      }
    }

    .airBtn {
      width: 100%;
      margin-top: 10px;
      font-weight: normal;
      color: #303133;
      background: #f0f2f5;
      border: none;
      border-radius: 4px;
    }
  }

  .save {
    width: calc(100% - 16px);
    height: 40px;
    margin: 8px;
    background: #1989fa;
    border-radius: 4px;
  }

  .airline-setting {
    position: relative;
    justify-content: space-between;

    :deep(.address .el-input__wrapper) {
      height: 32px;
      line-height: 32px;
    }

    .du {
      position: absolute;
      top: 0;
      right: -8px;
    }
  }

  .airline-slider {
    display: flex;
    align-items: center;
    margin: 10px 0;

    .el-button {
      width: 16px;
      height: 16px;
      padding: 0 5px 2px;
      font-size: 16px;
      color: #fff;
      background: #c0c4cc;
      border: none;
      border-radius: 50%;
    }

    :deep(.el-slider__button) {
      width: 11px;
      height: 11px;
      border: none;
    }
  }
}

.search-input {
  box-shadow: 0 2px 6px rgb(0 0 0 / 30%);
}

.search-results {
  position: absolute;
  top: 80px;
  left: 20px;
  z-index: 999;
  width: 400px;
}

.result-item {
  padding: 10px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
}

.result-item:hover {
  background-color: #f5f5f5;
}

.result-name {
  margin-bottom: 5px;
  font-weight: bold;
}

.result-address {
  font-size: 12px;
  color: #666;
}

.result-distance {
  margin-top: 5px;
  font-size: 12px;
  color: #409eff;
}

.airline-stoproute {
  cursor: pointer;
  padding: 12px;
  margin: 8px;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;

  .blue {
    color: #409eff;
  }

  .bgimg {
    margin: 0 4px 0 4px;
    background-color: rgb(242 242 242 / 14.9%);
    border: 1px solid #dcdfe6;
    border-radius: 2px;

    img {
      width: 25px;
    }
  }

  // .bgimg:nth-child(5n) {
  //   margin: 0;
  // }

  .text {
    height: 34px;
    font-size: 14px;
    line-height: 34px;
  }
}

.airline-distanceblue {
  border: 1px solid #2f69eb;
}

.airline-wavy {
  padding: 10px;
  margin-bottom: 10px;
  font-size: 12px;
  background: #f0f2f5;
  // border: 1px solid #dcdfe6;
  border-radius: 5px;

  &:nth-child(2) {
    margin-top: 5px;
  }

  &:last-child {
    margin-bottom: 0; // 覆盖默认的 margin-bottom
  }

  img {
    width: 15px;
    height: 14px;
    margin-right: 5px;
  }
}

:deep(.el-select__selected-item.el-select__placeholder) {
  color: #303133;
}

:deep(.el-radio) {
  font-weight: normal;
  color: #303133;
}

:deep(.el-checkbox) {
  font-weight: normal;
  color: #303133;
}

.m-l-5 {
  margin-left: 5px;
}

:deep(.el-input__wrapper) {
  height: 20px;
  background: #e4e7ed;
  border-radius: 4px;
  box-shadow: none;
}

.bgimg {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

.bgimg:hover::after {
  // position: absolute;
  // bottom: 100%;
  // left: 50%;
  // padding: 6px 10px;
  // margin-bottom: 5px;
  // font-size: 14px;
  // white-space: nowrap;
  // content: '拍摄模式';
  // background: #fff;
  // border: 1px solid #e4e7ed;
  // border-radius: 4px;
  // box-shadow: 0 2px 12px 0 rgb(0 0 0 / 6%);
  // transform: translateX(-50%);
}

.el-slider {
  margin: 0 10px;

  :deep(.el-slider__bar) {
    background: linear-gradient(79deg, #00ccd0 0%, #3a6af0 100%);
    box-shadow: 0 0 8px 0 rgb(97 137 202 / 43%);
  }
}

.tips {
  position: absolute;
  top: -30px;
  width: 100%;
  min-width: 95px;
  padding: 3px;
  font-size: 14px;
  font-weight: 400;
  color: #303133;
  white-space: nowrap;
  background: #fff;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 6%);
}

// :deep(.el-tooltip__popper) {
// font-size: 14px;
//  font-weight: 400;
// color: #303133;
// border: 1px solid #E4E7ED;
// }

:deep(.el-checkbox__label) {
  padding-left: 4px;
}

:deep(.custom-confirm-box) {
  .el-message-box__btns .el-button--small {
    padding: 8px 16px;
    font-size: 14px;
  }
}

.backbtn {
  position: absolute;
  bottom: 10px;
  width: calc(100% - 20px);
  font-size: 14px;
  font-weight: 500;
  line-height: 40px;
  color: #fff;
  text-align: center;
  cursor: pointer;
  background: #2f69eb;
  border-radius: 4px;
}

.sortable-item:hover {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.sortable-item:first-child {
  margin-top: 10px;
}

/* 系列和型号列表样式 */
.list {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  margin-bottom: 10px;
}

.list-item {
  padding: 8px 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  text-align: center;
  min-height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;

  &:hover {
    background: #e3f1ff;
    border-color: #1989fa;
    color: #1989fa;
  }

  &.active {
    background: #e3f1ff;
    border-color: #1989fa;
    color: #1989fa;
  }

  &::marker {
    content: none;
  }
}

/* 无人机品牌、系列、型号选择器样式 */
.select-container {
  position: relative;
  margin-bottom: 12px;
}

.select-label {
  display: block;
  margin-bottom: 6px;
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

/* 标记样式 */
.mark-icon {
  position: absolute;
  left: -22px;
  top: 50%;
  transform: translateY(-50%);
  background-color: #1989fa;
  color: white;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  z-index: 1;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 响应式处理 */
@media (max-width: 500px) {
  .list {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 350px) {
  .list {
    grid-template-columns: 1fr;
  }
}
</style>